关于javascript:Js下载图片解决跨域问题

55次阅读

共计 518 个字符,预计需要花费 2 分钟才能阅读完成。

function downloadImage(imgsrc, name) {const image = new Image();
    // 解决跨域 Canvas 净化问题
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        const event = new MouseEvent('click');
        a.download = name || 'photo';
        a.href = url;
        a.dispatchEvent(event);
    };
    image.src = imgsrc;
}

正文完
 0