Solve the getImageData() error: the canvas is contaminated by cross-domain data
P粉343141633
2023-08-29 12:52:11
<p>My code runs fine on localhost but not on the website. </p>
<p>I get this error from the console, for this line <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>Part of my code:</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>Note: </strong>My image URL (src) comes from a subdomain URL</p>
As others have said, you are "polluting" the canvas by loading from a cross-origin domain.
https://developer.mozilla.org/en-US/docs/ HTML/CORS_Enabled_Image
However, you can prevent this by simply setting:
This only works if the remote server correctly sets the following headers:
Dropbox file picker when using the Direct Link optionThis is a good example. I'm using this at oddprints.com to suck images from a remote dropbox image URL into my canvas and then submit the image data back to my server. All written in JavaScript