解决getImageData()错误:画布被跨域数据污染的问题
P粉343141633
2023-08-29 12:52:11
<p>我的代码在本地主机上运行得很好,但在网站上却无法运行。</p>
<p>我从控制台收到此错误,对于这一行 <code>.getImageData(x,y,1,1).data</code>:</p>
<pre class="brush:php;toolbar:false;">Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.</pre>
<p>我的代码的一部分:</p>
<pre class="brush:php;toolbar:false;">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;
}</pre>
<p><strong>注意:</strong>我的图像网址 (src) 来自子域网址</p>
正如其他人所说,您通过从跨源域加载来“污染”画布。
https://developer.mozilla.org/en-US/docs/ HTML/CORS_Enabled_Image
但是,您可以通过简单地设置来防止这种情况:
只有当远程服务器正确设置以下标头时,这才有效:
使用“直接链接”选项时的 Dropbox 文件选择器这就是一个很好的例子。我在 oddprints.com 上使用它来将远程保管箱图像网址中的图像吸到我的画布中,然后将图像数据提交回我的服务器。全部用 JavaScript 编写