vue html2canvas用法

1. 安装

Install NPM

npm install --save html2canvas

Install Yarn

yarn add html2canvas

2. 使用

import html2canvas from 'html2canvas'

1

2

3

4

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

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

  <slot></slot>

</div>

slot里面是你需要转化为图片的DOM元素。

1

2

3

4

5

data() {

  return {

    dataURL: ''

  }

},

dataURL是最后转化出来的图片base64地址,放在img标签中即可展示。

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;

  });

}

}

html2canvas的用法非常简单,不过1.0.0已经将写法改为了promise,在.then方法里获取canvas对象。

3.常见bug

1. 生成出来的图片有白色边框

在配置项里配置backgroundColor: null即可。

2. 有图片显示不出来并有报错(一般是跨域的错)

这是最常见的一个bug,就是这个插件无法生成跨域了的图片,也看了官方文档配置了也百度了都没有好的办法,最后是让后端直接把跨域的图片转成base64,就完美解决了这个问题。

3. 生成图片后会在原始DOM上覆盖而产生一个闪动的效果

先让生成的图片隐藏,等生成好以后再展示。(没有在手机上测试,效果不一定令人满意)

4.经典版本(0.5.0)常见bug

1.生成的图片模糊
2.有跨域图片导致生成的图片不完整

这两个问题网上百度都有很多解决办法。

html2canvas在vue下的巨坑

使用

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)

});

如果你要配置一些参数可以在传入dom的后面进行 object 传参 官网文档可查

猜你喜欢

转载自blog.csdn.net/Mr_linjw/article/details/85280831