/**
*
* @param {String} requestUrl 图片路径
* @param {String} saveFileName 保存的图片名称
* @param {String} fileFormat 图片格式 如:png, jpg, jpeg
*/
function imgDownload(requestUrl, saveFileName, fileFormat) {
saveFileName = saveFileName || "image";
fileFormat = fileFormat || "png";
const img = document.createElement('img');
img.src = requestUrl;
img.setAttribute("crossOrigin", "Anonymous");
img.onload = function () {
const a = document.createElement("a");
a.setAttribute("download", saveFileName);
a.href = getImageDataURL(img);
a.click();
};
function getImageDataURL(img) {
let canvas, ctx;
const width = img.width;
const height = img.height;
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
return canvas.toDataURL("image/" + fileFormat, 1);
}
}
有跨越问题看这篇文章:
https://blog.csdn.net/weixin_40647516/article/details/102660374