web 网络图片下载

代码 

imgDownload() {
  let imgUrl = this.imgList[this.actIndex].url;
  let imgName = this.imgList[this.actIndex].name;
  let image = new Image();  
  image.setAttribute("crossOrigin", "anonymous"); // 关键部分
  image.src = imgUrl;
  image.onload = () => {
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    let witdh = image.width;
    let height = image.height;
    canvas.width = witdh;
    canvas.height = height;
    context.drawImage(image, 0, 0, witdh, height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    let event = new MouseEvent("click"); // 创建一个单击事件
    a.download = imgName || "photo"; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.dispatchEvent(event); // 触发a的单击事件
  }
},

注: 图片服务端请求头中需要有'Access-Control-Allow-Origin' :"*"

你可能感兴趣的:(js)