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; }