Lately I’ve been experimenting with the new HTML5 Canvas element, and the best way to learn some new technology is to create something in it. For some time I’ve been dabbling in Processing and thought of porting some algorithms there in Canvas.
Rather than jumping into animation it was better to play around with static structures. I’ve a soft spot for visualizations so I decided to port some algorithms for creating recursive tree structures.
Before to go further you can view the demo and also download the code. The demos will only run in browses that support the Canvas element.
Downloads : 3098 / File size : 0 B
Drawing a tree
The simplest way to draw a tree is with the following code. This will render the tree with the default options.
The ‘algoTree.js’ exposes a single method, tree.draw, that accepts six parameters as given below.
tree.draw(ctx, height, width, spread, show leaves, leaves type);
‘ctx’ is the canvas context.
‘height/width’ is the canvas height and width.
‘spread’ takes a number between 0.3 – 0.9 and adjusts the size of the tree.
‘show leaves’ takes a boolean value and displays the leaves if set to true.
‘leaves type’ takes one of the following four parameters-
By default the trees are drawn with leaves but you can draw bare skeletal tree by passing the boolean value ‘false’ as the fourth parameter in the tree.draw method.