使用html2canvas下载图片
安装
npm i html2canvas
导入
import html2canvas from 'html2canvas'
用法
<button class="restore-btn" @click="saveImage('html2canvas', 'imgName')">生成图片</button>
<div id="html2canvas" ref="html2canvas">截取内容</div>
//图片格式转换方法
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 });
},
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);
});
},
转载
原文