vue html2canvas usage

1. Installation

Install NPM

npm install --save html2canvas

Install Yarn

yarn add html2canvas

 

2. Use

import html2canvas from 'html2canvas'

1

2

3

4

<div class="imageWrapper" ref="imageWrapper">

  <img class="real_pic" :src="dataURL" />

  <slot></slot>

</div>

Inside the slot are the DOM elements that you need to transform into images.

1

2

3

4

5

data() {

  return {

    dataURL: ''

  }

},

dataURL is the base64 address of the last converted image, which can be displayed in the img tag.

1

2

3

4

5

6

7

8

9

10

11

methods: {

 

toImage() {

  html2canvas(this.$refs.imageWrapper,{

    backgroundColor: null

  }).then((canvas) => {

    let dataURL = canvas.toDataURL("image/png");

    this.dataURL = dataURL;

  });

}

}

The usage of html2canvas is very simple, but 1.0.0 has changed the wording to promise, and get the canvas object in the .then method.

3. Common bugs

1. The generated image has a white border

Configure backgroundColor: null in the configuration item.

2. There are pictures that cannot be displayed and errors are reported (usually cross-domain errors)

This is the most common bug. This plug-in cannot generate cross-domain images. I have read the official documentation and configured it. Baidu has no good way. Finally, let the backend directly convert the cross-domain images to base64. It solves this problem perfectly.

3. After the image is generated, it will overwrite the original DOM and produce a flashing effect

Let the generated image be hidden first, and then display it after it is generated. (Not tested on mobile phones, the effect may not be satisfactory)

4. Common bugs in classic version (0.5.0)

1. The generated picture is blurred
2. The generated picture is incomplete due to cross-domain pictures

Baidu on the Internet has many solutions to these two problems.

The huge pit of html2canvas under vue

use

1

2

3

<div id="capture" style="padding: 10px; background: #f5da55">

  <h4 style="color: #000; ">Hello world!</h4>

</div>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

html2canvas(document.querySelector("#capture")).then(canvas => {

  document.body.appendChild(canvas)

});

  

```

  

![clipboard.png](/img/bVbghPZ)

  

```

html2canvas(document.querySelector("#capture") {

  async: true

}).then(canvas => {

  document.body.appendChild(canvas)

});

If you want to configure some parameters, you can perform object after passing in the dom. The documents on the official website can be checked.

Guess you like

Origin blog.csdn.net/Mr_linjw/article/details/85280831