preface

I believe there are a lot of friends in the development process to draw pictures, or screenshots, etc. Today I use in a summary to share with you, to avoid the pit.

Install html2canvas

npm i -D html2canvas
Copy the code

The introduction of html2canvas

Introduce HTML2Canvas on the components you want to use

import html2canvas from "html2canvas";
Copy the code

Add ref to get elements

HTML part:

<div class="m-html2canvas">
  <div ref="canvasRef" class="m-canvasRef">
    <div class="m-imageList" v-for="item in imageList" :key="item.id">
      <img :src="item.path" alt="" />
    </div>
  </div>
  <div class="m-showImage" v-if="imgUrl">
    <img :src="imgUrl" alt="" />
  </div>
  <div class="m-btn">
    <el-button type="primary" @click="createImageQrcode">Synthetic images</el-button>
  </div>
</div>
Copy the code

The data section:

imageList: [
  {
    path: "FM = https://t7.baidu.com/it/u=1595072465, 3644073269 & 193 & f = GIF".id: 1
  },
  {
    path: "FM = https://img2.baidu.com/it/u=3231735899, 2029570314 & 253 & FMT = auto&app = 138 & f = JPEG? W = 800 & h = 500".id: 2
  },
  {
    path: "FM = https://t7.baidu.com/it/u=1956604245, 3662848045 & 193 & f = GIF".id: 3}].imgUrl: ""
Copy the code

The methods section:

For details on html2Canvas configuration items, see the official website

methods: {
    createImage() {
      this.$nextTick(() = > {
        const canvas = document.createElement("canvas");
        // Get the DOM element to generate the image
        let canvasDom = this.$refs.canvasRef;
        // Get the specified width and height
        const width = parseInt(window.getComputedStyle(canvasDom).width);
        const height = parseInt(window.getComputedStyle(canvasDom).height);
        // console.log(" get the specified width and height ", width, height)
        // Double width and height to handle image blur
        canvas.width = width;
        canvas.height = height;
        canvas.style.width = width / 2 + "px";
        canvas.style.height = height / 2 + "px";

        const context = canvas.getContext("2d");
        context.scale(1.1);
        // context.fillStyle = '#FFFFFF'
        context.fillRect(0.0, canvas.width, canvas.height);
        const options = {
          backgroundColor: null.canvas: canvas,
          useCORS: true.// The configuration allows cross-domain
          // scale:1,
          // windowWidth: document.body.scrollWidth,
          // windowHeight: document.body.scrollHeight,
          // x: 0,
          // y: window.pageYOffset,
          // allowTaint: true,
          // background: "# FFFFFF ", // Make sure to add a background color, otherwise the image will be transparent
          dpi: 300 // Handle ambiguity
        };
        console.log("Get the specified width and height", width, height, canvas);
        html2canvas(canvasDom, options)
          .then(canvas= > {
            try {
              // Generate the image address
              this.imgUrl = canvas.toDataURL("image/png");
              console.log("canvas.toDataURL('image/png')".this.imgUrl);
            } catch (e) {
              alert("Image cross domain, save failed");
            }
          })
          .catch(err= > {
            console.log("Draw failed"); }); }); }}Copy the code

Style part

.m-html2canvas {
  display: flex;
}
.m-canvasRef {
  width: 500px;
  height: 500px;
  /* border: 1px solid red; * /
  /* box-sizing: border-box; * /
  box-shadow: 10px 10px 5px #888888;
}

.m-imageList {
  width: 500px;
  height: calc(500px / 3);
}

img {
  width: 100%;
  height: 100%;
  float: left;
}

.m-showImage {
  margin-left: 50px;
  background: red;
  width: 500px;
  height: 500px;
}

.m-btn {
  margin-left: 50px;
}
Copy the code

The above is a simple html2Canvas screenshots used. There will be a problem here, because the generated picture is base64, when the base64 address is copied, the bottom of the picture will lose part of the white, but it is normal to display directly in the page, so far I have not found the reason.

Cross-domain problem

Cross-domain problems still occur after useCORS = true is configured, for example:

There are two solutions:

First: the backend needs to set the HTTP response header on the server IIS, the most simple and rude method is to set all the *, but this is also low security, you can set according to their own needs:

access-control-allow-credentials:true
Access-Control-Allow-Headers:*
access-control-allow-origin:*
Copy the code

The second: < img > set crossorigin=”anonymous” on the img tag, but this will not work, we will still report cross-domain problems, and finally add a timestamp after the SRC image address, some people say that we need to add a fixed parameter, otherwise there is no cache, will keep asking, because our page renders, There are terms for negotiated caching and strong caching, mostly used to reduce the number of times a page is refreshed and to prevent multiple requests to the server when we visit Github at home. But when I used it, I found that adding a fixed parameter still gave me cross-domain problems.

. <img :src="staffQrCodeDialogBg1 + '? ' + new Date().getTime()"
      alt=""
      crossOrigin="anonymous"/ >...Copy the code

I generally use the second kind, front-end self-solving, fast, high efficiency

conclusion

Html2canvas pit filling tour is completed in this way, a total of three problems, picture blur problem, cross domain problem, picture bottom blank problem

This year I plan to force myself to summarize and learn, and plan some time to write articles to share what I have encountered and learned, to help everyone avoid falling into a pit.