公众号 canvas base64 另存为 图片 本地 下载 保存
思路是:html2canvas截图canvas的图像保存为base64,base64在专为blob,放到a标签下即可下载保存到本地
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<div id="codepic">
<canvas></canvas>
</div>
<button onclick="download()">保存图片</button>
window.download=function (){
new html2canvas(document.getElementById('codepic')).then(canvas => { //id="codepic"是需要截图的区域
// canvas为转换后的Canvas对象
let oImg = new Image();
oImg.src = canvas.toDataURL(); // 导出图片
// document.getElementById('tupian').appendChild(oImg); // 将生成的图片添加到body
var date = new Date();
var aLink = document.createElement("a"); // 创建一个a标签
var blob = base64ToBlob(canvas.toDataURL());
var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
aLink.download = date.getTime() + "." + blob.type.split("/")[1]; // 使用时间戳给文件命名
aLink.href = URL.createObjectURL(blob);
aLink.click();
// base64转Blob对象
function base64ToBlob(code) {
var parts = code.split(";base64,");
var contentType = parts[0].split(":")[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uint8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return new Blob([uint8Array], {type: contentType});
}
});
}
另存为图片需要点击右上角用本地浏览器访问后才能保存