1.template 中的代码
按钮触发保存图片 (这里使用的是 element ui)
- <el-button icon="el-icon-download" circle type="mini" @click="saveImage('Top3Img','工时最多前三原因')">
- </el-button>
- <div id="Top3Img" ref="Top3Img">
你需要截取的内容
</div>
2.methods 中的方法
- // 注意要在 script 标签前面引入 html2canvas
- import html2canvas from 'html2canvas';
- // 下面是 methods 中的内容
- // 图片转换格式的方法 直接使用就好 不需要知道为什么
- dataURLToBlob(dataurl) {
- let arr = dataurl.split(',');
- let mime = arr[0].match(/:(.*?);/)[1];
- let bstr = atob(arr[1]);
- let n = bstr.length;
- let u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new Blob([u8arr], { type: mime });
- },
- /* 保存图片的方法 (即按钮点击触发的方法)
- 第一个参数为需要保存的 div 的 id 名
- 第二个参数为保存图片的名称 */
- saveImage(divText, imgText) {
- let canvasID = this.$refs[divText];
- let that = this;
- let a = document.createElement('a');
- html2canvas(canvasID).then(canvas => {
- let dom = document.body.appendChild(canvas);
- dom.style.display = 'none';
- a.style.display = 'none';
- document.body.removeChild(dom);
- let blob = that.dataURLToBlob(dom.toDataURL('image/png'));
- a.setAttribute('href', URL.createObjectURL(blob));
- // 这块是保存图片操作 可以设置保存的图片的信息
- a.setAttribute('download', imgText + '.png');
- document.body.appendChild(a);
- a.click();
- URL.revokeObjectURL(blob);
- document.body.removeChild(a);
- });
- },
来源: http://www.jianshu.com/p/d07f5382b975