Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
canvas绘制图片,由于浏览器的安全考虑,如果在使用canvas绘图的过程中,使用到了外域的图片资源,那么在toDataURL()时会抛出安全异常:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
解决方案1.
如果想使用toDataURL()生成图片文件的话,在canvas绘图过程中使用的图片应该是当前域下的。
解决方案2.
访问的服务器允许,资源跨域使用,也就是说设置了CORS跨域配置,Access-Control-Allow-Origin
然后在客户端访问图片资源的时候
var img = new Image(); img.setAttribute('crossOrigin', 'anonymous'); img.src = url;
实例说明:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <link href="../scripts/Bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <script src="../scripts/jquery-1.11.3.min.js"></script> <script src="../scripts/Bootstrap-3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <img src="http://www.gongjuji.net/favicon.ico" crossorigin="anonymous"/> <canvas id="canvasOne" width="200" height="200"></canvas> </div> <script> /* * 将canvas图片转换成图片,上传到服务器 */ var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, canvas.width, canvas.height); //添加外网图片 var img = new Image(); //设置图片跨域访问 //img.setAttribute('crossOrigin', 'anonymous'); img.onload = function () { //画图 ctx.drawImage(img, 0, 0, img.width, img.height); var data = canvas.toDataURL('image/jpeg'); alert(data); } //使用外网图片 img.src = 'http://www.gongjuji.net/favicon.ico'; </script> </body> </html>