Using HTML5 canvas.toDataURL to generate placeholder images

A while ago lewis had a great idea – an online tool to figure out the proportional height, when given a width and a particular proportion.

I’ve actually needed to use it 3 or 4 times since it was created around a month ago, so I was keen to get involved and implement some of the suggestions he received to make it better. One of the suggestions was that the tool should generate placeholder graphics, which developers can use whilst creating websites.

I was thinking PHP GD library, which could have quite easily have done the job. However, there are a few disadvantages with this:

  1. The user has to wait while the browser makes a request to the server and gets the response
  2. The server has to have the GD image library installed!
  3. The server has to do work to generate images – eating up your valuable CPU cycles
  4. The server has to temporarily store the generated image – using up disk space
  5. The request and response both use up bandwidth
  6. The tool wouldn’t work offline

All of which could be argued to be relatively inconsequential…but I wanted to do something fun. I decided to use the HTML5 canvas element to draw the placeholder graphic because, well, that sounded fun.

Canvas has a method called "toDataURL" which (as you can probably guess) encodes the content of the canvas as a data url. I spent a couple of hours in the evening knocking up a prototype utilising this functionality.

You may be thinking (when looking at the source for the prototype): "where’s the canvas"? What actually happens is that when you change the width or height using the input boxes, the page dynamically creates a canvas element, draws the placeholder graphic inside, calls toDataURL and then creates an <img> tag, whose "src" attribute is set the data url we got from the canvas. The page then removes the canvas element and the old placeholder graphic, and appends the new graphic to the DOM. The process is so fast you don’t ever see the canvas element on the page.

The reason we don’t just leave the canvas on the page is because we want users to be able to save these graphics. You can’t right click on a canvas and select "Save image as…".

The only disadvantage I can think of by using this method is that it won’t work on older browsers…or browsers without javascript enabled. Ok that is two. Other than that, it’s great:

  1. The user doesn’t have to wait for a round trip to the server to complete
  2. The server does no further work other than to serve the script file
  3. No bandwidth is consumed transferring the image
  4. The tool even works offline!

To me, that sounds like WIN.