核心代码:
var funDownload = function (domImg, filename) { // 创建隐藏的可下载链接 var eleLink = document.createElement('a'); eleLink.download = filename; eleLink.style.display = 'none'; // 图片转base64地址 var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var width = domImg.natureWidth; var height = domImg.natureHeight; context.drawImage(domImg, 0, 0); // 如果是PNG图片,则context.toDataURL('image/png') eleLink.href = context.toDataURL('image/jpeg'); // 触发点击 document.body.appendChild(eleLink); eleLink.click(); // 然后移除 document.body.removeChild(eleLink); };推荐原文: http://www.zhangxinxu.com/wordpress/?p=6252(By大神zhangxinxu)