HTML and CSS Reference
var r = randInt(255), g = randInt(255), b = randInt(255);
ctx.strokeStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.lineWidth = 2;
// Center the initial branches
The exterior method randomSnowflake generates a number of random property values setting the num-
ber of branches, spread angle, size, level of recursion, and a random color for the snowflake. It then calls the
recursive method drawSnowflake , which draws a single line for each branch rotated to the correct angle and
then sets up the transformation matrix for the child branches. It then checks if there are more levels to draw, and
if so, calls itself again with some updated parameters.
Because all drawing calls are wrapped in ctx.save() and ctx.restore() calls, each branch can pass
along its transformation matrix to its child branches without affecting any of the other ones.
Each time you click the Canvas, a new snowflake generates. The variety of possibilities by just drawing some
lines and varying a few parameters shows the power of nested transforms.
Applying Canvas Effects
As this chapter wraps up, there are a couple additional effects worth covering that Canvas provides: shadows
and composition effects.
The Canvas context provides a way to add drop shadows to any drawn element, including text, rectangles, paths,
and images. This is controlled via a set of four properties on the context:
// CSS color shadow, accepts RGBA, RGB, hexadecimal
ctx.shadowColor = "rgba(255,255,255,0.5)";
ctx.shadowOffsetX = 4; // horizontal shadow offset
ctx.shadowOffsetY = 4; // vertical shadow offset
ctx.shadowBlur = 10; // distance for shadow to fade out
You can use shadows to generate normal drop-shadow effects by using darker shadowColor values or
give a subtle glow effect by setting the shadow offset values to zero and using a lighter color.