通过html2canvas将dom节点内容导出为图片的实现方法
项目使用的vue2技术栈,所以也以vue2来做演示
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 41 42
| import html2canvas from 'html2canvas'
async exportImage(){ let container = this.$refs.dashContainer let imgData = await this.convertToImage(container) const a = document.createElement('a'); a.href = imgData; a.setAttribute('download', 'chart-download'); a.click(); },
convertToImage(container, options = {}){ const scale = window.devicePixelRatio;
const _width = container.offsetWidth; const _height = container.offsetHeight; let { width, height } = options; width = width || _width; height = height || _height;
const ops = { scale, useCORS: true, allowTaint: false, ...options };
return html2canvas(container, ops).then(canvas => { return canvas.toDataURL("image/png"); }); },
|