Canvas. CORS. Codepen.
Published: 29 Sep 2013
I’m going to be working on a project that might require some fancy combining of images to make one image on-the-fly, as well as some simple animation and other “flashy” stuff. Finally, a real perfect reason to learn HTML5 canvas!
I set aside some time to hack away at it with some tutorials and decided to use Codepen as my playground. I’m assuming the project will involve receiving some image files for the end web product, so I went with that scenario. First, I grabbed some simple icon images from Raphael, used SVG-edit to export them as PNGs, and uploaded them to imgur to easily reference on Codepen.
The ol’ college try
Which worked great. The canvas showed the icon. Awesome! I’m rollin’! And then I tried adding this:
and got this lovely in the console: Uncaught SecurityError: An attempt was made to break through the security policy of the user agent.
FAIL. Sounds serious, eh?
Apparently, when you pull in a resource from an external domain, or cross-domain, and use it on the canvas, the canvas becomes “tainted” and will no longer allow you to pull data out of it. The good news for me is that I’m pretty sure for my project the images will be local on the same server that the web page lives on.
But, I couldn’t leave it there. I wanted to figure out how to get around the tainted canvas if I ever did have a real use case for doing so. I found this short article on MDN that described exactly the problem I was having and offered a solution. The domain that serves the image files must also serve the proper CORS headers. Basically, the CORS header has to specify that the domain that is using the image is OK to use it.
Try, try again
Codepen PRO has asset hosting, but I
comments powered by Disqus