fredag 7 mars 2008

drawing a tree with javascript and svg

Hmm, my back is hurting and I should stay away from the laptop, but instead I've been playing around with svg and javascript to create graphics from grammars, very similar to contextfreeart.

rule("start", 2,
line,
c("start", {x: 100, r: 15, s: 0.8}),
c("start", {x: 100, r: -35, s: 0.8}));

rule("start",
line,
c("start", {x: 100, s: 0.8}));

This is a small grammar to draw a tree. The first rule specify that we draw a line, and then we call the rule "start" twice, with two transformations (read more on contextfreeart to understand) that rotate the tree 15 degress right and 35 degrees left, creating two branches. The second rule specifies to draw a line and continue forward. (the s-parameter is used to scale down the tree, making the branches smaller and smaller).

I've created a page where you can create your own programs. Maybe I'll document it some more later.

rule("start",
square,
c("start", {x: 100, r:6, s: 1.01}));

start("start",
{x:300, y:300, s:0.01})

Here is a small example that creates a spiral (replace the existing code with this). It exemplifies that you can specify the start-position of the graph. Click on the step buttons to render more of the spiral. The available primitives are line, square, circle. The code is also available here.

Have fun!

Update: Added support for color. You can specify the start color as an optional third argument to start, and add color transforms when calling rules, adding and subtracting color values. Here is an example using colors.

rule("c", 0.2, circle)
rule("c", circle, c("c", {x:100, blue: 10}))

rule("s",
circle,
c("c", {x:100, red: 20}),
c("s", {y:100, x:30, r: 15, s:0.9})
)

start("s", {x:300, y:200, r:120, s:0.2},
{red: 200, blue: 10, green: 10})

Inga kommentarer: