canvas绘图时遇到的跨域问题

7,444 阅读2分钟
当在canvas中绘制一张外链图片时,我们会遇到一个跨域问题。
示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>crossorigin</title>
</head>
<body>
    <canvas width="600" height="300" id="canvas"></canvas>
    <img id="image" alt="">
    <script>
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        var image = new Image();
        image.onload = function() {
            ctx.drawImage(image, 0, 0);
            document.getElementById('image').src = canvas.toDataURL('image/png');
        };
        image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg';
    </script>
</body>
当在浏览器中打开这个页面时,你会发现这个问题:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
这是受限于 CORS 策略,会存在跨域问题,虽然可以使用图像,但是绘制到画布上会污染画布,一旦一个画布被污染,就无法提取画布的数据,比如无法使用使用画布toBlob(),toDataURL(),或getImageData()方法;当使用这些方法的时候 会抛出上面的安全错误

这是一个苦恼的问题,但幸运的是img新增了crossorigin属性,这个属性决定了图片获取过程中是否开启CORS功能:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>crossorigin</title>
</head>
<body>
    <canvas width="600" height="300" id="canvas"></canvas>
    <img id="image" alt="">
    <script>
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        var image = new Image();
        image.setAttribute('crossorigin', 'anonymous');
        image.onload = function() {
            ctx.drawImage(image, 0, 0);
            document.getElementById('image').src = canvas.toDataURL('image/png');
        };
        image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg';
    </script>
</body>
对比上面两段JS代码,你会发现多了这一行:
image.setAttribute('crossorigin', 'anonymous');

就是这么简单,完美的解决了!