JavaScript点击按钮下载图片,涉及同源下载和跨域下载

以下内容适用于同源下载图片:

参考:https://blog.csdn.net/Thea12138/article/details/82801375

function download(src) {
    var $a = document.createElement('a');
    $a.setAttribute("href", src);
    $a.setAttribute("download", "");
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
    $a.dispatchEvent(evObj);
}

对于跨域的图片,使用上述方法只会打开一个新窗口显示要下载的图片,不会打开下载窗口,下载方法如下:

参考:https://segmentfault.com/q/1010000017159631

https://blog.csdn.net/visionke/article/details/84583105

    function ddd(){        
        var src = 'http://pic.c-ctrip.com/VacationH5Pic/mice/wechat/ewm01.png';
        var canvas = document.createElement('canvas');
        var img = document.createElement('img');
        img.onload = function(e) {
            canvas.width = img.width;
            canvas.height = img.height;
            var context = canvas.getContext('2d');
            context.drawImage(img, 0, 0, img.width, img.height);         
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
            canvas.toBlob((blob)=>{
                let link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = 'aaa'; 
                link.click();  
            }, "image/jpeg");           
        }
        img.setAttribute("crossOrigin",'Anonymous');
        img.src = src;
    }

 

你可能感兴趣的:(js爬坑系列)