1 /** 2 * @description 下载图片 3 * @author cq 4 * @Date 2020-04-15 17:29:22 5 * @LastEditTime 2020-04-20 14:01:39 6 * @LastEditors cq 7 */ 8 const downloadIamge = (imgsrc, name) => {//下载图片地址和图片名 9 const image = new Image(); 10 // 解决跨域 Canvas 污染问题 11 image.setAttribute("crossOrigin", "anonymous"); 12 image.onload = function () { 13 const canvas = document.createElement("canvas"); 14 canvas.width = image.width; 15 canvas.height = image.height; 16 const context = canvas.getContext("2d"); 17 context.drawImage(image, 0, 0, image.width, image.height); 18 const url = canvas.toDataURL("image/png"); //得到图片的base64编码数据 19 const a = document.createElement("a"); // 生成一个a元素 20 const event = new MouseEvent("click"); // 创建一个单击事件 21 a.download = name || "photo"; // 设置图片名称 22 a.href = url; // 将生成的URL设置为a.href属性 23 a.dispatchEvent(event); // 触发a的单击事件 24 }; 25 image.src = imgsrc + "?" + new Date().getTime(); 26 } 27 28 export default downloadIamge