Currently I’m trying to get a bit more JavaScript and HTML5 exposure (no use denying it I guess – it’s here to stay) and found the Paper.js framework which seems to be really nice.

An easy way to test a vector-based framework often are fractals where you can get visual pleasing images that are easy to generate and are often very taxing on the frameworks and render-engines.

# The fractal’s construction

The easiest one I can think of is Sierpinski’s triangle:

It’s really easy to generate:

given 3 Points (of a triangle) A, B, C just create the midpoints on AB, AC and BC and create 3 new triangles (A, AB, AC), (AB, B, BC) and (AC, BC, C) from it – repeat recursively for each of those and you’ve got your fractal:

# Implementing this using Paper.js

After all this is very straight-forward, as Paper.js is capable of performing basic vector.operations – so all there is to do is including the paper.js script into your page, adding a canvas-element in the body and doing the drawing in a special “text/paperscript” script:

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Simple Fractal with Paper.Js</title> <script type="text/javascript" src="Assets/paper.js"></script> <script type="text/paperscript" src="Fractal.js" canvas="myCanvas"></script> </head> <body> <canvas id="myCanvas" resize="true"></canvas> </body> </html>

Here is the code for the fractals-drawing (fractal.js):

function genFractal (a, b, c, depth) { if (depth == 0) drawTriangle(a, b, c); else { var ab = (a + b) / 2; var ac = (a + c) / 2; var bc = (b + c) / 2; genFractal(a, ab, ac, depth - 1); genFractal(ab, b, bc, depth - 1); genFractal(ac, bc, c, depth - 1); } } function drawTriangle(a, b, c) { var path = new Path(); path.strokeColor = 'red'; path.moveTo(a); path.lineTo(b); path.lineTo(c); path.lineTo(a); } genFractal(new Point(10, 610), new Point(610, 610), new Point(310, 10), 7);

As you can see it’s very easy – just create the new points, generate another iteration of triangles and draw them on the final recursion depth – this will produce the red triangle you see above.