Cross Domain Canvas Images

By  on  

You can do some really awesome stuff with images when you push their data into canvas.  And of course, when you're done playing around with the image, you can export the canvas data to an IMG element and data URI.  What we sometimes don't remember, however, is that the cross-origin rules apply to those images, so if you try to convert an image from another host to canvas, you'll get an error.  You can use this snippet from HTML5 Boilerplate within the image host domain's .htaccess file to allow cross-origin data reading of images:

<IfModule mod_setenvif.c>
	<IfModule mod_headers.c>
		<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
			SetEnvIf Origin ":" IS_CORS
			Header set Access-Control-Allow-Origin "*" env=IS_CORS
		</FilesMatch>
	</IfModule>
</IfModule>

Allowing for CORS within .htaccess then allows you to pull image data when the image is on another domain. This is especially useful on CDNs! .htaccess is a life-saver sometimes!

Recent Features

Incredible Demos

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Create a Simple Dojo Accordion

    Let's be honest:  even though we all giggle about how cheap of a thrill JavaScript accordions have become on the web, they remain an effective, useful widget.  Lots of content, small amount of space.  Dojo's Dijit library provides an incredibly simply method by which you can...

Discussion

  1. I’m finding that I get CORS errors when I request from my own site and then convert them to base64 images using the “canvas technique” referred to here. Is that expected?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!