Web原生下载图片

downloadImage() {
    let canvas = document.createElement('canvas')
    let context = canvas.getContext('2d')
    let image = new Image()
    image.crossOrigin = 'anonymous'
    image.src="http://img.ping.net/code16202674817594?e=1620285836&token=wQe4r6-qNt8fr40r-ZS7q05QB3jSXQLdqoibqXR0:UdIwEZn_ZpcbcD4y2sPLoCb47aw="
    image.onload = function() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        canvas.height = this.height
        canvas.width = this.width 
        context.drawImage(this, 0,0,this.width, this.height)
        console.log(context)
        let url = canvas.toDataURL('image/jpeg')
        let link = document.createElement("a");
        link.href = url
        link.download = '22.jpeg'
        link.style.display = "none";//a标签隐藏
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link)
    }
}

你可能感兴趣的:(Web原生下载图片)