如何解决getImageData()错误画布已被交叉源数据污染? [英] How to fix getImageData() error The canvas has been tainted by cross-origin data?

查看:238
本文介绍了如何解决getImageData()错误画布已被交叉源数据污染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在我的本地主机上工作得很好,但它不能在网站上工作。



我从控制台得到这个错误,对这行 .getImageData(x,y,1,1).data

 未捕获的SecurityError :无法在'CanvasRenderingContext2D'上执行'getImageData':画布已被跨源数据污染。 

我的部分代码:

  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;
返回this.target.getContext('2d')。getImageData(x,y,1,1).data;
}

注意:我的图片网址(src)是from a subdomain url

解决方案

正如其他人所说,你是通过从一个跨域来加载污染 p>

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



然而,您可以通过简单设置来防止这种情况:

  img.crossOrigin =Anonymous; 

只有远程服务器适当地设置以下标题才可以使用:

  Access-Control-Allow-Origin*

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

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

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. 

part of my code:

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;
    }

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 "*"

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 :)

这篇关于如何解决getImageData()错误画布已被交叉源数据污染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆