<el-button type="danger" @click="handleDownLoad('https://picsum.photos/500/500', '图片名称')">下载</el-button>
// 下载图片03
const download = (href, name) => {
let eleLink = document.createElement("a");
eleLink.download = name;
eleLink.href = href;
eleLink.click();
eleLink.remove();
};
// 下载图片02
const downloadByBlob = (url, name) => {
let image = new Image();
image.setAttribute("crossOrigin", "anonymous");
image.src = url;
image.onload = () => {
let canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, image.width, image.height);
canvas.toBlob((blob) => {
let url = URL.createObjectURL(blob);
download(url, name);
// 用完释放URL对象
URL.revokeObjectURL(url);
});
};
};
// 下载图片01
const handleDownLoad = (url, name) => {
const iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = url;
document.body.appendChild(iframe);
setTimeout(() => {
document.body.removeChild(iframe);
}, 200);
// 下载图片
downloadByBlob(url, name);
};