如何解决cavans图片getImageData、toDataURL跨域呢?

188 阅读1分钟

如何解决cavans图片getImageData、toDataURL跨域呢?

  • 方法一: 使用new Image的方式,设置crossOrigin属性
const getImgInfo = function (url) {
    return new Promise (resolve => {
        const img = new Image();
        img.src = url;
        img.crossOrigin = '';
        img.onload = function () {
            console.log('读取图片信息成功了---');
            resolve({
                img,
                width: img.width,
                height: img.height
            })
        }
        img.onerror = function (err) {
            console.log(err, '失败了=====');
        }
    })
}
  • 方法二:使用new XMLHttpRequest的形式,发起一个请求获取Bold的形式
const getImgInfo = function (url) {
    return new Promise (resolve => {
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            const blobArr= [];
            blobArr.push(this.response);
            const middleUrl = URL.createObjectURL(new Blob(blobArr));
            const img = new Image();
            img.src = middleUrl;
            img.onload = function () {
                console.log('读取图片信息成功了---');
                // 这里及时释放掉
                URL.revokeObjectURL(middleUrl);
                resolve({
                    img,
                    width: img.width,
                    height: img.height
                })
            }
            img.onerror = function (err) {
                console.log(err, '失败了=====');
            }
        }
        xhr.open('GET', url, true);
        xhr.responseType = 'arraybuffer';
        xhr.send();
    })
}
  • 最后使用:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>如何解决cavans图片getImageData、toDataURL跨域呢?</title>
</head>
<body>
    <script>
        const url = 'https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&fmt=auto&app=138&f=JPEG?w=632&h=500';

        // 使用上面的方法
        getImgInfo(url).then(info => {
            const { img, width, height } = info;
            let canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);
            ctx.fillStyle = '#f00';
            ctx.font = '40px serif';
            ctx.fillText('我是canvas画出来的', 20, height - 30);
            // 上面不处理跨域,这里toDataURL的时候会出现跨域
            const result = canvas.toDataURL('image/png', 0.5);
            let testImg = document.createElement('img');
            testImg.src = result;
            document.body.appendChild(testImg);
            testImg = null;
            canvas = null;
        });
    </script>
</body>
</html>