vue 中 html2canvas模块使用注意事项

安装:

npm install html2canvas --save

引入:

import  html2canvas from   'html2canvas'

使用:

html:

  /*截图容器*/

      /*图片跨域使用注意点1:图片路径加时间戳, 添加crossOrigin="anonymous" 属性*/

      /*联系上文 qrcode 使用 */

js:

let _this = this

let ref = this.$refs.faultTree // 截图区域

html2canvas(ref, {

      backgroundColor: '#fff',

      useCORS: true    /*图片跨域使用注意点2:配置跨域 useCORS: true  */

}).then((canvas) => {

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

      console.log(dataURL)   /*画成的图片*/

      _this.dataURL = dataURL

}).catch( () => {

    _this.$api.msg("生成失败")

})

这里有几个关键的地方:

allowTaint: true 和 useCORS: true 都是解决跨域问题的方式,不同的是使用allowTaint 会对canvas造成污染,导致无法使用canvas.toDataURL 方法,所以这里不能使用allowTaint: true

在跨域的图片里设置 crossOrigin="anonymous" 并且需要给imageUrl加上随机数

canvas.toDataURL('image/jpg') 是将canvas转成base64图片格式。



2019.12.5补充:

此方法只适用于H5端,app 和小程序会报错

替代的可用canvas画图保存海报,详见 uni-app用canvas截屏并且分享好友

你可能感兴趣的:(vue 中 html2canvas模块使用注意事项)