vue 使用 html2canvas将DOM转化为图片

1、前言html

如今项目开发中将DOM转化为图片是一个很常见的需求。因而决定使用html2canvas这个插件。PS:版本比较多,这里介绍最新版。npm

2、代码canvas

1.安装插件后端

npm install html2canvas --save

2.使用(这里页面里的图片class="pic"是随机取的,因此生成的图片不是特定的)跨域

<template>
  <div class="wrap">
   /** DOM最后生成的图片*/
   <img class="posterImg" v-show="dataURL.length>20" :src="dataURL"/>

   /** 须要转化为图片的DOM,因为PicUrl不是特定的,因此ref不能写固定值*/
   <div :ref="ImgRef" style="position:absolute;left:0;top:0;z-index:0">
     <h1>小鱼蕾蕾</h1>
     <img class="pic" :src="PicUrl" />
   </div>
  </div>
</template>

<style scoped>
.wrap {
  width: 100%;
  height: 100vh;
  overflow-y: scroll;
  background-color: #fff;
  text-align: center;
  position: relative;
}
.posterImg{
  width: 100%;
  height: auto;
  position: absolute;
  left:0;
  top:0;
  z-index: 2;
}
.pic {
  width: 100%;
  height: auto;
  display:block;
}
</style>

如下dataURL是最后转化出来的图片base64地址,放在img标签中便可展现。dom

<script>
export default {
  name: 'getImg',
  data(){
    return{
     dataURL:"", //DOM生成的图片
     RandomNum:1, //随机数
     ImgRef:"", //DOM的ref
     PicUrl:"", //页面里的随机图片
     ImgArr:[
	  ./static/img1.png,
	  ./static/img2.png,
	  ./static/img3.png,
     ]
    }
  },
  beforeRouteEnter: (to, from, next) => {
      //does NOT have access to `this` component instance
      next(vm => {
        vm.Instance();
      });
  },
  beforeRouteUpdate: function(to, from, next) {
      next();
      this.Instance();
  },
  menthod:{
    Instance(){
     //生成随机整数 [0, 2]
     this.RandomNum = Math.floor(Math.random() * (2 - 0 + 1) + 0);
     this.ImgRef = "PosterImg"+this.RandomNum;
     this.PicUrl = this.ImgArr[this.RandomNum-1];
  
     setTimeout(()=>{
	    this.GetPosterUrl();
     },3000)
  },

   //把html生成图片
   GetPosterUrl(){
    let ImgRef = "PosterImg"+this.RandomNum;
    this.$nextTick(() => {
      html2canvas(this.$refs[ImgRef], {
      allowTaint: true,
      backgroundColor: null // 解决生成的图片有白边
    }).then(canvas => {
      let dataURL = canvas.toDataURL("image/png");
      this.dataURL = dataURL;
      console.log(this.dataURL);
    });
   });
  }
 }
}
</script>

3、常见bugpost

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

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

2.有图片显示不出来并有报错(通常是跨域的错)插件

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

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

先让生成的图片隐藏,等生成好之后再展现。

4.图片截取不全

(1).资源较多,形成模块并无彻底加载完毕,就已经生成了截图;加个定时器进行延时操做

setTimeout(()=>{
	  this.GetPosterUrl();
   },3000)

(2).页面超过一屏时,生成图片是若是直接从document.body上截取,只能截取到可视区域。因此从内部DOM上截取,可是此种状况下,若是滚动屏幕,截取图片不对。

解决方法:让滚动属性设置在最外层的元素(.wrap)上,而不是在body上

.wrap{
  width: 100%;
  height: 100vh;
  overflow-y: scroll;
  background-color: #fff;
  text-align: center;
  position: relative;
}
相关文章
相关标签/搜索