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

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

Incredible Demos

  • By
    iPhone-Style Passwords Using MooTools PassShark

    Every once in a while I come across a plugin that blows me out of the water and the most recent culprit is PassShark: a MooTools plugin that duplicates the iPhone's method of showing/hiding the last character in a password field. This gem of...

  • By
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

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!