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:
- The user has to wait while the browser makes a request to the server and gets the response
- The server has to have the GD image library installed!
- The server has to do work to generate images – eating up your valuable CPU cycles
- The server has to temporarily store the generated image – using up disk space
- The request and response both use up bandwidth
- 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 user doesn’t have to wait for a round trip to the server to complete
- The server does no further work other than to serve the script file
- No bandwidth is consumed transferring the image
- The tool even works offline!
To me, that sounds like WIN.