Canvas跨域:Tainted canvases may not be exported.

2021-11-08 10:21:17 浏览数 (1)

canvas 绘制跨域图片,导出为图片的时候会出现 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

解决方案

代码语言:javascript复制
var image = new Image();
image.crossOrigin = '';//重点设置跨域
image.onload = function (e) 
{
$('#myCanvas').attr('width', this.width);
$('#myCanvas').attr('height', this.height);
ctx.drawImage(this, 0, 0, this.width, this.height, 0, 0, this.width, this.height)        
}
image.src ='IMGURL'
//导出为png图片
var exportImg = cvs.toDataURL("image/png", 1);
$('#imgs').attr('src', exportImg);//设置src为base64的图片

设置头部可跨域

header("Access-Control-Allow-Origin: *");

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/HTML/CORS_enabled_image

0 人点赞