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