## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# Canvas and Recursive Drawing

One benefit of immediate mode drawing is the lack of an intervening data structure that we’d have to create and manipulate to keep track of drawing elements; with immediate mode drawing, you can just fire and forget drawing commands, layering them as thick as you like. This makes Canvas particularly useful for high-density, recursive drawing functions like fractals. Recursive functions are defined as those that call themselves. By feeding the last set of results generated by a function back into the function itself, we create a kind of software feedback loop. The following example calls itself recursively 10 times:

```var rescurse(value1, value2) {
value1−−;
value2++;
if (value1 <= 0) return;
recurse(value1, value2);
};
recurse(10,0);```

The previous example is not particularly exciting, but it demonstrates two important aspects of recursive functions:

• Values are adjusted within the recursive function and fed back into it.

• We need a test to break out of otherwise infinite recursive loops.

Instead of applying simple increments and decrements, what if we did something more interesting involving a little bit of trigonometry and some random elements? Figure 6-14 shows a recursively drawn tree that uses simple Canvas-line drawing commands. The natural-looking effect is a recognizable feature of recursive graphical functions. Notice how the final tips of the branches look very refined and thin. This is due to the previously discussed fractional pixel anti-aliasing.

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required