function downloadImage(imgsrc, name) {
const image = new Image();
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function () {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
const url = canvas.toDataURL('image/png');
const a = document.createElement('a');
const event = new MouseEvent('click');
a.download = name || 'photo';
a.href = url;
a.dispatchEvent(event);
};
image.src = imgsrc;
}
方法二:
function downloadImage(imgsrc, name) {
const a = document.createElement('a');
a.href = `${imgsrc}?response-content-type=application/octet-stream`;
a.download = name || '';
a.click();
a.remove();
}
最稳妥的方案是后端给接口下载图片
我理解通过href和src下载是类似于jsonp的跨域解决方式,但这两种方法好像都有些情况仍然是跨域的。。。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。