Drawing Trees in Canvas

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.

Download

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.

VIEW DEMO

Download Source
Downloads : 2887 / 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.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Trees in Canvas</title>
<script type='text/javascript' src='algoTree.js'></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var height = 500, width = 400;
var canvas = document.getElementById('canvas');
canvas.height = height;
canvas.width = width;
ctx = canvas.getContext("2d");
tree.draw(ctx,height,width);
 </script> 
</body>
</html>

Below are a few generated samples.

Usage

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-
tree.SMALL_LEAVES
tree.MEDIUM_LEAVES
tree.BIG_LEAVES
tree.THIN_LEAVES

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.

4 thoughts on “Drawing Trees in Canvas

  1. The routine to draw the leaves is at lines 125-132 in the ‘algoTree.js’ file. Try changing the lengthFactor variable and the color.

Comments are closed.