共计 777 个字符,预计需要花费 2 分钟才能阅读完成。
html2canvas 将 html 元素转为图片
html2canvas(element,options).then((canvas) =>{})
基本使用
scale:缩放比例, 默认为 1
allowTaint:是否允许跨域图像污染画布,默认为 false
useCORS:是否尝试使用 CORS 从服务器加载图像,默认为 false
width:canvas 画布的宽度, 默认为 jQuery 对象的宽度
height:canvas 画布的高度, 默认为 jQuery 对象的高度
backgroundColor:/ 画布的背景色,默认为透明(#fff), 参数可以为 #表示的颜色,也可以使用 rgba
- 忽略某元素
在某元素加上以下属性信息即可
data-html2canvas-ignore="true"
npm install html2canvas
html2canvas(this.$refs.imageDom, { backgroundColor: null, useCORS: true }).then(canvas => {
setTimeout(() => {
this.createFile(canvas.toDataURL("image/png"))
}, 0)
}).catch(error => {
});
易错点
- 生成图片区域中的 dom 元素中有 img 标签,生成图片后,img 图片加载不出来
- 添加 useCORS:true 属性;
- 给要生成 canvas 的 DOM 中包含的每一个 img 标签添加 crossorigin=”anonymous” 属性;
- 确保你的图片 CDN 服务器支持 CORS 访问,也就是会返回 Access-Control-Allow-Origin 等响应头。
- 不支持 box-show、box-radius
- 生成图片背景色异常,需要在异常的背景色处的 dom 块元素,设置背景色,一般设置为白色
原文地址: html2canvas 实现生成图片以及易出错点
正文完