canvas跨域:Tainted canvases may not be exported.

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. 

在使用canvas的toDataURL方法,如果图片跨域,会报如上错误。

解决方法是给image标签加一个允许跨域的属性:crossorigin="anonymous"。

<img crossorigin="anonymous" src="" alt="">
var imgurl = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1031893560,2135917576&fm=27&gp=0.jpg';
var canvas = document.createElement('canvas');
    canvas.width = 200;
    canvas.height = 200;
var ctx = canvas.getContext('2d');
var img = new Image();
    img.src = imgurl;
    img.setAttribute('crossorigin', 'anonymous'); // 注意设置图片跨域应该在图片加载之前
    img.onload = function () {
        ctx.drawImage(img, 0, 0, 200, 200);
        document.body.appendChild(canvas);
        var canvastourl = canvas.toDataURL();
        console.log(canvastourl);
    }

移动端可能不适配,还是需要将图片有后台工程师帮我们转换为同源的图片。

 

参考:

canvas跨域问题 - 伶丶AM - 博客园 https://www.cnblogs.com/Amcc/p/7110021.html

详解canvas绘图时遇到的跨域问题_html5教程技巧_脚本之家 https://www.jb51.net/html5/604662.html

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值