当前位置: 移动技术网 > IT编程>网页制作>Html5 > 详解canvas绘图时遇到的跨域问题

详解canvas绘图时遇到的跨域问题

2019年07月25日  | 移动技术网IT编程  | 我要评论

当在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');

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网