js canvas獲取圖片base64 dataUrl

function getImgBase64(path, callback) {
    var img = new Image();
    img.src = path;

    //圖片加載完成後觸發
    img.onload = function () {
        var canvas = document.createElement("canvas");
        //獲取繪畫上下文
        ctx = canvas.getContext("2d");

        // 獲取圖片寬高
        var imgWidth = img.width;
        var imgHeight = img.height;

        //設置畫布寬高與圖片寬高相同
        canvas.width = imgWidth;
        canvas.height = imgHeight;

        //繪製圖片
        ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
        //圖片展現的 data URI
        var dataUrl = canvas.toDataURL('image/jpeg');
        callback ? callback(dataUrl) : '';
    };
}


getImgBase64('wood.png', function (dataUrl) {
    console.log(dataUrl);
});
相關文章
相關標籤/搜索