JS+Canvas繪畫&導出圖片

//下載圖片到本地
export function downloadIamge(imgsrc, name) {
    //下載圖片地址和圖片名
    var image = new Image();
    // 解決跨域 Canvas 污染問題
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        var _dataURL = canvas.toDataURL('image/png'); //獲得圖片的base64編碼數據

        var blob_ = dataURLtoBlob(_dataURL ); // 用到Blob是由於圖片文件過大時,在一部風瀏覽器上會下載失敗,而Blob就不會

        var url= {
            name: name || "圖片.png", // 圖片名稱不須要加.png後綴名
            src: blob_
        };

        if (window.navigator.msSaveOrOpenBlob) {   // if browser is IE
            navigator.msSaveBlob(url.src, url.name );//filename文件名包括擴展名,下載路徑爲瀏覽器默認路徑
        } else {
            var link = document.createElement("a");
            link.setAttribute("href", window.URL.createObjectURL(url.src));
            link.setAttribute("download", url.name + '.png');
            document.body.appendChild(link);
            link.click();
        }
    };
    image.src = imgsrc;

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }
}
相關文章
相關標籤/搜索