html2canvas导出指定内容图片和图片跨域透明背景设置
- 安装插件
1 | npm install --save html2canvas // yarn add html2canvas |
引入插件,给导出内容部分添加ref标记
关键代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41import html2canvas from 'html2canvas';
export default {
onExport() {
const clientWidth = this.$refs.imageWrapper.offsetWidth;
const clientHeight = this.$refs.imageWrapper.offsetHeight;
const wh = [clientWidth, clientHeight];
html2canvas(this.$refs.imageWrapper, { useCORS: true,logging:true }).then((canvas) => {
const dataURL = canvas.toDataURL('image/png');
this.download(dataURL, wh);
});
},
getUrlBase64(url, wh) {
return new Promise((resolve) => {
let canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'Anonymous'; // 允许跨域
img.src = url;
img.onload = () => {
// eslint-disable-next-line prefer-destructuring
canvas.height = wh[1];
// eslint-disable-next-line prefer-destructuring
canvas.width = wh[0];
ctx.drawImage(img, 0, 0, wh[0], wh[1]);
const dataURL = canvas.toDataURL('image/png');
canvas = null;
resolve(dataURL);
};
});
},
download(imgUrl, wh) {
this.getUrlBase64(imgUrl, wh).then((base64) => {
const link = document.createElement('a');
link.href = base64;
link.download = `自定义图片名字.png`;
link.click();
});
}
}图片跨域、背景透明配置
图片跨域问题
img标签的crossorigin=”anonymous”
useCORS: true
以上2个属性缺一不可,通过上面的两行代码就能解决html2canvas图片跨域问题
1
2
3
4
5html2canvas(this.$refs.imageDom, {
useCORS: true, // 图片跨域 同时img标签设置crossorigin="anonymous"
backgroundColor: null // null || "rgba(0,0,0,0)" 设置背景为透明色
scale: window.devicePixelRatio
})部分css的样式不能识别
1)背景混合模式
2)边框图像
3)盒子装饰打破
4)盒子阴影
5)筛选
6)字体变体连字
7)混合模式
8)对象适合
9)重复线性梯度
10)写作模式
11)飞涨
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Gardennias!
评论