下载图片到本地
/** * 下载图片到本地 * @param {String} domId img标签的id * @param {String} name 下载图片名称 */ function downloadCanvasIamge(domId, name){ let image = new Image() // 解决跨域 Canvas 污染问题 image.setAttribute('crossOrigin', 'anonymous') image.onload = function () { let canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height let context = canvas.getContext('2d') context.drawImage(image, 0, 0, image.width, image.height) let url = canvas.toDataURL('image/png') let a = document.createElement('a') let event = new MouseEvent('click') a.download = name || '下载图片' a.href = url a.dispatchEvent(event) } image.src = document.getElementById(domId).src }
简洁方式
const a = document.createElement('a') a.href = '图片地址,可以是base64' a.download = '下载图片' a.click()