Home  >  Q&A  >  body text

Solve the getImageData() error: the canvas is contaminated by cross-domain data

<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>
P粉343141633P粉343141633392 days ago508

reply all(1)I'll reply

  • P粉465675962

    P粉4656759622023-08-30 09:13:14

    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:

    img.crossOrigin = "Anonymous";

    This only works if the remote server correctly sets the following headers:

    Access-Control-Allow-Origin "*"

    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

    reply
    0
  • Cancelreply