Search code examples
javascripthtml5-canvasimage-manipulationcolor-picker

The Color Picker example on MDN is not working. And so is my code


On the Mozilla Developer Network page, there's an example where you can create a color picker with the help of getImageData(). You can check out the code at https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas#A_color_picker.

It seems to work fine on the MDN page. But on CodePen or JSFiddle, it's broken. I tried to follow the instruction with a similar problem, and I get this error when setting img.src to an url: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'. Hope someone can help me.


Solution

  • If you add this line in the JS section after the img src and reload the page, the example will work.

    img.crossOrigin = "Anonymous"
    

    It has to do with cross-origin contamination and HTML canvas. Apparently if an element comes from a different domain then the canvas becomes tainted and you can't pull data from it, unless you give set the correct cross origin attribute with the line above. This error could also happen if the headers weren't set on the image when it was sent from the source.

    There's more information at this blog post from CodePen: https://blog.codepen.io/2013/10/08/cross-domain-images-tainted-canvas/

    Here's a link to a CodePen that works!
    http://codepen.io/illuminatedspace/pen/WpWQmo?editors=1010#0