Home » Cool & Future Tech, Featured, Headline, html5, Web Experiments

Create CSS Rules from an HTML5 Canvas

24 July 2010 4 Comments
Create CSS Rules from an HTML5 Canvas

This thing caught me off guard but then I tried it, it worked so here it is: You’ll need a browser supporting CSS3 and Canvas for this post to make any sense. I tested with Chrome & Firefox.

What’s the difference between the two blocks below?
Answer: One’s a canvas and the other are div tags.

Hello
Canvas
World
Que pasa?








This might not seem that interesting at first so here’s the interesting bit: The Div’s background is actually taken from the Canvas. There’s only one Canvas on the page so how’s that working?
Answer: A CSS class is dynamically created with its background set to the base64 output of the Canvas!

Yes, you can get the base64 encoding of any canvas element using canvas.toDataURL().

var base64 = canvas.toDataURL("image/png");

This was news to me but the connection was that the base64 data can then be used in a new CSS rule to with the data being the background, just like you’d do with a tiny image.

* Side note: It’s common to base64 encode images and directly embed them into the CSS file provided they are small enough. Base64 encoding is typically 33% larger than the binary data but you save the HTTP request. If you Sprite your images into one big file it’s less of a savings. Again, all things in engineering are a balance/compromise so do what makes sense for your situation.

var newClass = ".newClass{  background:url("+base64+");} ";
$("<style type='text/css'>"+size + newClass + "</style>").appendTo("head");

I then rotated the divs with CSS3 just for kicks.

<div style="-webkit-transform: rotate(-10deg); -moz-transform: rotate(-10deg); transform: rotate(-10deg);">Hello</div>

Here’s the relevant code all in one piece:


// grab the data
var base64 = canvas.toDataURL("image/png");

var newClass = ".newClass{  background:url("+base64+");} ";

$("<style type='text/css'>" + newClass +"</style>").appendTo("head");

$('#box div').addClass("newClass");

So why would you ever do this? I suppose you might do this to avoid creating a lot of smaller canvas tags. I haven’t checked but I’d wager the overhead for a canvas is higher than that of a CSS rule. You can create one canvas image and then use it all over the place with CSS.

You could implement rounded corners with this but it’s probably the most complex way of doing rounded corners ever so wouldn’t recommend it there either.

One possible use of this is to take a copy of an image as it’s being built. E.g. Canvas images are bitmaps and there’s no “undo”. Unlike SVG, they don’t modify the DOM so you can’t add and remove elements of the image. Imagine a graph built using Canvas, if the user modifies the graph it might be useful to take a copy of it before the modification. You could do this by dumping the base64 data and displaying as a CSS image, rather than creating a 2nd canvas element. I’m reaching here but you get the idea.

I’m not sure this will ever have a practical application. For now it’s just an interesting tech experiment and another example of the cool stuff possible with HTML5.

4 Comments »

  • Advait said:

    While I am still trying to think of a scenario where this could be appliedm this is an interesting departure from previous ideas…HTML5 is shaping up pretty nice..

  • Rajesh Pillai said:

    This is cool. Francis, did you had a chance a look at this site

    http://10k.aneventapart.com/

    Its about a challenge of building an app under 10 kilobytes using HTML5..

  • Francis (author) said:

    I have not seen that. In my day, we had a 1kb challenge in C and assembler and you would not believe some of the stuff folks were able to do. Most of the apps had built in self-compression so when you ran the app it would “inflate” itself but on disk it was < 1kb.

  • Rajesh Pillai said:

    Cool..

    Also here’s another HTML5 Boiler Plate http://html5boilerplate.com/.

    This may be of interest… Some of the features extracted from the website is outlined below..

    * Cross-browser compatible (Supports for IE6 as well)
    * HTML5 ready. Use the new tags with certainty.
    * Optimal caching and compression rules for grade-A performance
    * Best practice site configuration defaults
    * Mobile browser optimizations
    * Progressive enhancement graceful degradation … yeah yeah we got that
    * IE specific classes for maximum cross-browser control
    *…

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.