js 获取图片base64 兼容 ie

// 获取图片base 64
function getImgBase64(path, callback) {
    if (window.navigator.userAgent.indexOf("MSIE")>=1) {
        // ie
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var url = URL.createObjectURL(this.response);
            var img = new Image();
            img.onload = function () {
                // 此时你就可以使用canvas对img为所欲为了
                // ... code ...
                let canvas = document.createElement("canvas");
                //获取绘画上下文
                let ctx = canvas.getContext("2d");

                // 获取图片宽高
                let imgWidth = img.width;
                let imgHeight = img.height;

                //设置画布宽高与图片宽高相同
                canvas.width = imgWidth;
                canvas.height = imgHeight;

                //绘制图片
                ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
                //图片展示的 data URI
                let dataUrl = canvas.toDataURL('image/jpeg');
                callback ? callback(dataUrl) : '';

                // 图片用完后记得释放内存
                URL.revokeObjectURL(url);
                document.body.appendChild(canvas);
                // // 然后移除
                document.body.removeChild(canvas);
            };
            img.src = url;
        };
        xhr.open('GET', path, true);
        xhr.responseType = 'blob';
        xhr.send();
    } else {
        //   not ie 
        var img = new Image();
        img.src = path;
        img.setAttribute("crossOrigin", 'anonymous')

        //图片加载完成后触发
        img.onload = function () {
            let canvas = document.createElement("canvas");
            //获取绘画上下文
            let ctx = canvas.getContext("2d");

            // 获取图片宽高
            let imgWidth = img.width;
            let imgHeight = img.height;

            //设置画布宽高与图片宽高相同
            canvas.width = imgWidth;
            canvas.height = imgHeight;

            //绘制图片
            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
            //图片展示的 data URI
            let dataUrl = canvas.toDataURL('image/jpeg');
            callback ? callback(dataUrl) : '';

            document.body.appendChild(canvas);
            // // 然后移除
            document.body.removeChild(canvas);
        };
    }
}
微信截图_20191010161040.png

https://www.cnblogs.com/sunala/p/7085525.html

你可能感兴趣的:(js 获取图片base64 兼容 ie)