To change my mind tonight, I was looking into a way to use the <canvas> element to do something you’ll find probably useless: displaying the HTML5 logo in 3D on the top left of my blog. It’s sometimes so much fun to play with code just for your own pleasure.
Well, it was very straightforward and simple to put in place. Luckily, I’ve found the excellent Kevin Roast website who has written a simple 3D engine based on the HTML5 <canvas> element. He has also built an animated 3D version of the HTML5 logo here: http://www.kevs3d.co.uk/dev/html5logo/
After doing some little modifications and merging some of his sample code, I’ve obtained what you’re currently seeing on this page. If your browser doesn’t support <canvas>, here is a screenshot of the output under IE9:
I’ve also inserted it inside my 2 first articles on SVG & Canvas (in French):
- Introduction aux APIs graphiques d’HTML5: SVG & Canvas (1/4)
- Introduction aux APIs graphiques d’HTML5: SVG & Canvas (2/4)
If you’re navigating into the page, you’ll see also that the little logo is following the vertical scrolling.
If you’d like also to disturb your readers by displaying this little 3D useless thing, you simply have to copy/paste these 3 lines at the end of your page to import the needed scripts:
And you’re done!
If you’re curious and if you’d like to quickly analyze how these scripts work, you just have to press the F12 key which will display the integrated IE9 development bar. In the Script section, select the k3d-min.js file in which you’ll find the main logic that handle the 3D engine with Canvas. You’ll notice by the way that the file is completely unreadable as it has been minified. IE9 offers you an interesting option to reformat the code:
The second interesting script is included inside the html5logo.js file which executes some code at the end of the loading of your page. It creates the <canvas> element by code, add it at the end of the document tree and display it at the top left corner using in-line CSS. The code then instantiates the k3d engine and asks it to display the 3D HTML5 logo thanks to 5 faces.
For instance, here is the code for the first face:
var obj1 = new K3D.K3DObject();
drawmode = "solid";
shademode = "lightsource";
sortmode = "unsorted";
addphi = -0.5;
abouty = OBJMOVEY;
scale = OBJSCALE;
perslevel = 1000;
This will output this face:
And voilà! Have fun and have a nice HTML5 week-end!