Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save austinhappel/5398013 to your computer and use it in GitHub Desktop.
Save austinhappel/5398013 to your computer and use it in GitHub Desktop.
You're creating a `<canvas>` app and you're pulling images from external sources (e.g. http://notyourdomain.com/image/foo.jpg) and you want to create a bitmap of the new image via the canvas **toDataUrl**. You will get a **DOM security error 18** most likely. Here is a workaround.

Cross origin images with canvas and toDataUrl()

Problem:

You're creating a <canvas> app and you're pulling images from external sources (e.g. http://notyourdomain.com/image/foo.jpg) and you want to create a bitmap of the new image via the canvas toDataUrl. You will get a DOM security error 18 most likely.

Solution:

You must have control over what headers the image source sends.

  1. When loading images, make sure the image has the attribute crossorigin set to anonymous.

     img.setAttribute('crossorigin', 'anonymous')
    
  2. Ensure that all images from your source are sent with this header added:

     Access-Control-Allow-Origin: *
    

    You might also want to add this line, but it did not make any difference in my case:

     Access-Control-Allow-Credentials: true
    

Important note: Once you set the cross origin attribute on the image, you will no longer be able to load in images that are served without the "Access-Control-Allow-Origin' header added.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment