<img src="" /img>
<button onclick="handleDownloadClick">下载图片</button>
function handleDownloadClick() {
var eleLink = document.createElement('a');
eleLink.download = 你的文件名 + '.jpg';
eleLink.style.display = 'none';
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var width = domI mg.naturalWidth;
var height = domImg.naturalHeight;
canvas.width = width;
canvas.height = height;
context.drawImage(domImg, 0, 0);
eleLink.href = canvas.toDataURL('image/jpeg');
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
}
但是,当 img 图片的 url 跨域的时候,会在新窗口打开,chrome 并不执行下载,
需要给 img 标签加一个属性:crossOrigin
<img crossOrigin="anonymous" src="" />