利用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();
});
},
}修改背景图片
1
2
3html2canvas(this.$refs.imageDom, {
backgroundColor: null // null 表示设置背景为透明色
})部分css的样式不能识别
1)背景混合模式
2)边框图像
3)盒子装饰打破
4)盒子阴影
5)筛选
6)字体变体连字
7)混合模式
8)对象适合
9)重复线性梯度
10)写作模式
11)飞涨
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Gardennias!
评论