本週有個需求是將HTML渲染好的頁面生成圖片,用戶在微信端使用的時候可以保存到相冊。因而一頓搜索猛如虎以後,發現html2canvas這個插件可以解決。由於項目中用到的框架是vue,這裏就討論一下在vue中如何使用html2canvas。html
Install NPMvue
npm install --save html2canvas
複製代碼
Install Yarnnpm
yarn add html2canvas
複製代碼
我在這裏使用的是1.0.0版本canvas
<template>
<img :src="htmlUrl" v-show="!isShow" class="canvas-img"/>
<div ref="imageTofile">
<div>
<!須要使用html2canvas繪圖的html部分---->
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas' // 引入html2canvas
export default {
data(){
return {
htmlUrl:'',//html2canvas繪製好的圖片地址
isShow:false //在頁面dom渲染完畢後讓圖片顯示在用戶界面
}
},
methods:{
toImage () {
// 第一個參數是須要生成截圖的元素,第二個是本身須要配置的參數,寬高等
html2canvas(this.$refs.imageTofile, {
backgroundColor: null,
useCORS: true // 解決文件跨域問題
}).then((canvas) => {
let url = canvas.toDataURL('image/png');
this.htmlUrl = url;
if(this.htmlUrl){
this.isShow = true;//繪圖完畢讓圖片顯示
}
})
},
}
}
</script>
複製代碼
這裏有個坑就是在頁面沒有徹底渲染完畢的狀況下,在移動端上下拉動頁面會出現頁面元素位置不許確或者圖片生成不完整的狀況,所以加上判斷條件,讓頁面渲染完畢以後使html2canvas繪製好的圖片顯示出來能夠避坑。跨域