Steve Fitzpatrick
Business owner, HTML builder, Xboxer, idea generator, dad, wireframer, greyhound owner, UX guy, Celtic fan, grumpy old man.
TwitterSearch
Client-side dynamic images with Canvas
You can use HTML5's Canvas to create dynamic images in the browser. No server processing needed.
In a past life as a despot on a football forum, I used to create emoticons for players at the club. I'd put them together in Photoshop, save them and then upload them to the server. There was sufficient faffing around that when faced with six or seven to do, I never quite got around to it. While reading the excellent book Introducing HTML5 I found out that the content of a canvas element (onto which you can overlay almost anything) can be converted to a single image with a single command. Awesome. Here is the example (by Remy Sharp) http://introducinghtml5.com/examples/ch05/todataurl.html And this is what I managed to put together. It's experimental, so you WILL NEED either Chrome (recommended), Safari or Opera to see it working.http://celticend.co.uk/icons/ So, what's going on? Inputs
Nothing of note going on here... just using a traditional form to capture some data.
And most of the code... There are two things of interest here. Firstly, I am using the HTML5 placeholder attribute to show "Player Surname" in the input box. This will populate an input box with greyed out text which disappears on focus. Obviously, it's not supported by all browsers at the moment, but is a nice touch when it doesn't have to work across them all. Secondly, the value of the select field relates to the CCTLD country code for each flag that I have on my server. Annoyingly (but understandably), canvas will throw a security error if you try to convert it to an image when it contains another image that is sourced from an external site. For instance, if you use a dynamic Google Chart in your canvas, you will not be allowed to then convert that canvas to a flat image. The Output
When you fill out the details, you are rewarded with your image. And that is an image, a bona fide right-click-and-save-as image. Created completely in the user's browser. How does it work?
The image at the bottom is just that, an image. To get to that stage, I've had to
- Read the inputs from the form
- Draw the background boxes onto the canvas element
- Draw the text on the canvas element
- Show the element containing my output image
- Convert the canvas to an image SRC and attach that to the output image
Note, the image that you see there isn't the canvas element, that's hidden on the page throughout. But it looks identical.
Viewing the codeYou can have a look at the code in the page source for the example. It's very self-explanatory. The nicest bit is the convert-to-image, and this piece of code deals with that particular magic If there's demand, I can go through each step.
view-source:http://celticend.co.uk/icons/ Love

Comments (0)
Leave a comment...