代码如下:
const dataURL = canvas.toDataURL({
format: "png",
width: 400,
height: 400,
});
const link = document.createElement("a");
link.download = new Date().getTime();
link.href = dataURL;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
结果虽然文件是下下来了,但是浏览器出现以下报错
解决方法,改成
const dataURL = canvas.toDataURL({
format: "png",
width: 400,
height: 400,
});
const link = document.createElement("a");
let blob = dataURLtoBlob(dataURL);
let url = URL.createObjectURL(blob);
link.download = new Date().getTime();
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 将Base64字符串转换为Blob对象
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
简言之,就是把
link.href = dataURL;
改成
let blob = dataURLtoBlob(dataURL);
let url = URL.createObjectURL(blob);
link.href = url;