Posts Tagged ‘HTML5 Canvas

02
Nov
11

Creative Javascript – 3D Tree with Leaf-fall

A HTML5 prototype…

Finally getting around to have a play with HTML5 Canvas – enabled by attending Seb Lee Delisle’s excellent CreativeJS course.

I’m impressed with performance from Canvas nowadays – my first sight of it many moons ago left me pretty disappointed – but now it actually feels useful and some pretty impressive visual effects can be achieved without resorting to WebGL.

The prototype I threw together here demonstrates a growing tree, in 3D with numerous branches, leaves, leaf fall, faux-shading and colour phasing. The demo will re-grow a tree on mouse click, and will allow for left and right rotation by means of mouse position (left/right).

creativeJS

3D Tree with Leaf Fall

To talk through the code a little: The tree is constructed using a recursive buildBranch function. Every branch spawns two new branches, or in the last generation it has a 90% chance of spawning a leaf. The branches are coloured from brown to green related by the recorded generation of the branch.

No 3D libraries were used in this demo – all of the 3D is via a simple scaling calculation for 3D points [ fov / (fov + point.z) ]. This allows for any 3D point to be translated (scaled) onto the 2D canvas.

The Painter’s Algorithm (priority fill) is applied via the sorting of all branches and leaves on their mid-point. This means that those furthest away are drawn to screen first.

Shading is applied by mapping colour to the z value of a branch’s position. This is very simply applied. There is a related alpha to add a fog effect to the furthest away elements, this gives some subtle but nasty artefacts and could be improved.

When a branch is fully grown the leaves will then appear and grow to their full size. When they fall a sine value is applied to rotation to make it rock as it falls. Leaves will collect on the ground.

Performance is pretty good here, but I did have to restrict the number of branch generations to 9. Of course some of the out-of-the-box features that Flash has such as Glow and Blur filters don’t exist – which means work-arounds or approximations have to be used – sound implementation isn’t very consistent across browsers – it is still early days, more and more JS will be used across the web, as it is the browser manufacturers will hopefully drive their products into more useful areas and consistent implementations.

The demo is a fast turn-around ‘prototype’, so not optimal or well formed. Feel free to have a play with the code, offer improvement suggestions or adapt in anyway you wish.

No attempt has been made to cover HTML5 cross-browser issues – so don’t expect this to work in IE!

Direct Link: 3D Tree with Leaf Fall




Categories

Reasons to be Creative 2012

FITC Amsterdam 2012

Flash on the Beach 2011

Flash on the Beach 2010

Flash on the Beach 2009

Swingpants at FOTB2009

Twitter Updates


Follow

Get every new post delivered to your Inbox.