如何修复 getImageData() 错误画布已被跨域数据污染?

2022-01-17 00:00:00 javascript html html5-canvas

我的代码在我的本地主机上运行良好,但在网站上却无法运行.

My code is working very well on my localhost but it is not working on the site.

我从控制台收到此错误,对于这一行 .getImageData(x,y,1,1).data:

I got this error from the console, for this line .getImageData(x,y,1,1).data:

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. 

我的部分代码:

jQuery.Event.prototype.rgb=function(){
        var x =  this.offsetX || (this.pageX - $(this.target).offset().left),y =  this.offsetY || (this.pageY - $(this.target).offset().top);
        if (this.target.nodeName!=="CANVAS")return null;
        return this.target.getContext('2d').getImageData(x,y,1,1).data;
    }

注意:我的图片 url (src) 来自子域 url

Note: my image url (src) is from a subdomain url

推荐答案

正如其他人所说,您通过从跨域域加载来污染"画布.

As others have said you are "tainting" the canvas by loading from a cross origins domain.

https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

但是,您可以通过简单的设置来防止这种情况发生:

However, you may be able to prevent this by simply setting:

img.crossOrigin = "Anonymous";

这仅在远程服务器正确设置以下标头时才有效:

This only works if the remote server sets the following header appropriately:

Access-Control-Allow-Origin "*"

使用直接链接"选项时,Dropbox 文件选择器是一个很好的例子.我在 oddprints.com 上使用它来将远程 Dropbox 图像 url 中的图像存储到我的画布中,然后将图像数据提交回我的服务器.全部在javascript中

The Dropbox file chooser when using the "direct link" option is a great example of this. I use it on oddprints.com to hoover up images from the remote dropbox image url, into my canvas, and then submit the image data back into my server. All in javascript

相关文章