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

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!