ContextFree.js & Algorithm Ink: Making Art with Javascript
In honor of the the release of Firefox 3, I’m releasing ContextFree.js today, along with the demo site Algorithm Ink. ContextFree.js is about drawing striking images—and making art—with minimal amounts of code.
Computers programs lost something important when displaying a splash of color stopped being one line of code. As a kid, I remember being able to type “plot x,y” on the Apple II to throw up a phosphorescent splotch. When the simplicity of the one-line plotter went away, so did the delight at being so effortlessly generative—in a visual way—on the computer. ContextFree.js is a stab at making it easy again. It’s like a grown up version of Logo (or at least the Turtle Graphics part of Logo).
Go ahead and play with it on Algorithm Ink. It has goodies like a gallery to see other people’s art, the ability to view the source-code of any piece of art, and the ability to save the art to your desktop with a single right-click (that comes along for free, more on this in a second). It works best in Firefox 3, but should also work in Opera and Safari.
The inspiration and kick-in-the-pants motivation for this project came from the always-excellent John Resig (also of Mozilla) finally releasing Processing.js.
It’s All About the Javascripts
ContextFree.js is a port of Context Free Art by Chris Coyne. Algorithm Ink uses open-web, standards-based tools: no plugins required. It uses Canvas to to the drawing, and Javascript to compile and interpret the Context Free grammar. The code that does the compiling and render is open-source and available here. Handling thumbnails and other manipulations of images is just a couple lines of Javascript. No need to muck around with server-side black magic. With the addition of arbitrary transforms to Safari 3.1, all modern browsers, except IE, support Canvas fully enough to run ContextFree.js.
One of the great things about using open-web standards is that it plays nicely with user expectations. If you like a particular piece of art, you can just right click to save it as an image.
It would also be possible to use an image as the background for a blog—imagine a unique piece of art adorning your site, one that’s different for every visitor. The bleeding edge versions of Webkit have, in fact, implemented the ability to use Canvas with CSS. Open-web technology helps to break down the silos of inaccessibility: backgrounds images done with Flash have never been adopted because of the heavy-weight feel, as well as the lack of interoperability with the rest of the DOM. As Canvas takes becomes more wide spread, I’m looking forward to an explosion of infographics and other data visualizations that weren’t possible before without a heavy server-side setup, or without a compile step that breaks the ability to view-source-and-learn cycle of the web (Flash, Java, &c, I’m looking at you).
A Peak at the Syntax
The grammar is pretty simple. Let’s start by making a circle:
startshape shape
rule shape{
CIRCLE{}
}
This says start by drawing the rule named “shape”. The rule shape says to draw a circle.

Now let’s make things more interesting:
startshape shape
rule shape{
CIRCLE{}
shape{ s .5 b .2 x -.25 }
}
We’ve added a single line which says that part of the rule for “shape” is to draw itself, scaled down by half, with a slightly increased brightness, drawn on the left side of its parent circle. This makes an off-centered bulls-eye pattern.

Now let’s go to the right, as well as the left:
startshape shape
rule shape{
CIRCLE{}
shape{ s .5 b .2 x -.25 }
shape{ s .5 b .2 x .25 }
}

For comparison, this is what the equivalent code in Processing.js looks like:
// Processing.js code to make the same circle pattern.
void setup()
{
size(200, 200);
noStroke();
smooth();
noLoop();
}
void draw()
{
drawCircle(126, 170, 6);
}
void drawCircle(int x, int radius, int level)
{
float tt = 126 * level/4.0;
fill(tt);
ellipse(x, 100, radius*2, radius*2);
if(level > 1) {
level = level - 1;
drawCircle(x - radius/2, radius/2, level);
drawCircle(x + radius/2, radius/2, level);
}
}
It’s much longer, involves more setup, and more fiddly calculations. In fact, the entire ContextFree.js source is as long as the setup function. Of course, by simplifying so much in ContextFree.js, we’ve also removed the flexibility Processing.js affords.
Adding one more line of code gives an unexpected result: The Sierpinski Triangle. I’ll leave it as an exercise for the reader to figure out what that line of code is, but I doubt that it will be much of a puzzle.
Follow the mouse
The equivalent of “Hello, World!” for a graphical environment is a dot that follows the cursor, replete with a fading trail. This is what it looks like in ContextFree.js:
startshape DOT
rule DOT{
SQUARE{ s 4 b 1 a -.9 }
SQUARE{ s .3 }
}
rule MOUSEMOVE{
DOT{ }
}
We start by defining the rule “DOT” which draws two things: A large square (scaled up 4x), which is white (brightness of 1), and mostly transparent (alpha of -.9), and then a smaller black square. The large transparent white square acts to fade out more and more of the previous DOTs that have been drawn (it’s a standard trick for doing motion blur effects). The rule MOUSEMOVE simply draws a dot at the current mouse position, whenever the mouse moves.
Here’s the result.
There’s one more example that demonstrates the rest of the features that makes ContextFree.js powerful at the end of this post.
The Big Picture
Besides being pretty, why is ContextFree.js interesting? Because it shows the power of Open web technologies for making graphically-enabled, compelling interaction. The true power of the web revolves around anyone being able to dive in, see what someone else has done, and expand upon it. Canvas lowers the cost of entry to creating graphical mashups and other dynamic, graphical content. It also shows the progress the web has made: a year ago, this demo would not have been possible. Canvas wasn’t ready, and Javascript interpreters weren’t fast enough. Looking at the qualitative difference in speed from Firefox 2 to Firefox 3 indicates the amazing and substantial progress made towards speeding up Javascript since the last major browser release cycle.
Implementation
There are three major components to ContextFree.js: a tokenizer, a compiler, and a renderer. Each can be instantiated and used separately. The compiler returns a JSON object of the parsed code, which makes it easy to write a new front-end. I’d be interested to see if a Flash implementation of ContextFree.js would be faster than the pure Javascript, and if so, how much faster. As a side note, I’d also like to see an implementation of the Canvas API done in Flash, as a better replacement for excanvas for IE.
Because the computation and drawing of fractals can be intensive, the rendering occurs in it’s own threaded queue. How quickly it iterates over the shapes is dependent on how long the last drawing operation happened. This helps to keep ContextFree.js from freezing the browser.
There were a couple problems with browser inconsistencies and Canvas deficiencies that make the renderer interesting.
The first problem I ran into was that whilst the Canvas specification does support setting the transformation matrix, it does not support getting the transformation matrix. This means that if you want to know how large a shape will be when you draw it (for instance, to know when an element in a fractal is too small to be seen and is therefore safe to not draw), or want to draw in a threaded environment where you can’t guarantee a global transformation state, you need to re-implement the entire transformation infrastructure. This is a bad breakage of DRY, and slow from a development standpoint. According to Ian Hickson, the reason for the lack of a getter seems to stem from a possible implementation detail, although I don’t understand the argument. In personal communications with irrepressible Mozillian Vlad Vukićević, it appears that there is an possibility of adding the getter to the Firefox Canvas API.
The second problem I ran into was that versions of Safari older than 3.1 do not support setting the transformation matrix. The work around isn’t pretty. It involves taking the desired transformation matrix, de-convolving it into an equivalent set of rotations, scales, and translations, and then applying those base transforms to the Canvas. That’s a lot of math and eigen values. Luckily, Dojo already did the heavy lifting and I was able to stand on their shoulders for ContextFree.js.
The last problem I ran into is that even the latest editions of Safari do not support .setTransformation, which means that there is no call to return to reset the current transformation matrix to the identity. I used lead Webkit-developer Maciej Stachowiak’s solution, which is to save the pristine transformation state (using .save), perform the desired transformation and draw step, and then restore the pristine transformation state (using .restore).
The end result is that while there are inconsistencies, JS libraries can tide us over until us user-agents get fully in sync. That said, I recommend the addition of .getTransformation to the Canvas specification: it will save a lot of unnecessary code rewriting, most of which is matrix multiplication best done in a low-level language.
Improvments
There are a number of improvements to be made to both ContextFree.js and Algorithm Ink. With the former, it isn’t a full port (it’s missing things like comments, z-index, and loop notation). With the later, there is still a strong disconnect between a text-based input and a graphical output. I would love the ability for authors to indicate which variables are interesting in their code, and have the UI expose that variability through sliders and other graphical means. I’d also like to graphically teach the system rules: for example draw a couple shapes, group them, copy and scale them, and have Algorithm Ink generalize that as a rule, translate that rule to code, and draw the full fractal.
The ever-inspiring Bret Victor had some excellent suggestions that I hope someone takes up:
* Highlight a section of code (or “mark” a rule somehow), and the parts of the picture that were generated by by that code/rule are marked somehow—by applying a tint or a glow, perhaps. Because things are so recursive, you should be able to tell when a part of the picture has been marked multiple times—darker tint, eg. The idea is to be able to quickly explore a program and see what’s doing what.
* The opposite: put the mouse over a pixel, and see what code is responsible for that pixel. Ideally, you could see the entire call stack. Perhaps with annotated pictures so you can see what was drawn at each level of the call stack. Let the artist answer the question, “Why did this [part of the picture] happen?”
* Scrub through the construction of the pic. At each timestep, both the picture being added and the code responsible for it are highlighed. The current transform matrix is shown. I can step through time and understand what is happening and why.
Given that ContextFree.js’s “bytecode” is simply a JSON object, as I mentioned above, it wouldn’t be hard to write a new front-end. For example, here’s the “bytecode” for the “follow the mouse” example:
{
startshape:"DOT",
DOT:[
{
weight:1,
draw:[
{shape:"CIRCLE", s:4, b:1, a:-0.9},
{shape:"CIRCLE", s:0.33, b:1, a:-0.5},
{shape:"CIRCLE", s:0.3, b:0.5, sat:0}
]
}],
MOUSEMOVE:[{ weight:1, draw:[{shape:"DOT"}] }]
}
Get Involved
ContextFree.js is open source and hosted on Google Code. Feel free to jump in. Feel free to email me at my first name at mozilla.com.
Appendix A: Full Example
The last example adds demonstrates a couple more features that make ContextFree.js powerful:
startshape scale
rule scale{
spiral{s .1 y -.5 x 1}
}
rule spiral{
SQUARE{ a -.5 }
spiral{ y 1.5 r 10 s .99}
}
rule spiral .01 {
TRIANGLE{ }
spiral{ y 1.5 r 10 s .95}
spiral{ y 1.5 r 10 s .95 flip 90}
}
Let’s step through the code. The “scale” rule simply makes everything smaller and translates it down and to the right. Let’s look at the first rule “spiral”. It creates a half-transparent square, then makes a slightly smaller square that’s transposed and rotated ten degrees to the left. Repeating this gets a stepping-stone spiral. There are, however, two rules for “spiral”. This is where randomness comes into the design: whenever the rule “spiral” is encountered, ContextFree.js randomly chooses one definition among all definitions of that rule. The number after the rule name indicates the weight of the choice, where the default weight is 1. Thus, this rule draws something like this:

Modify the code slightly we can get an almost hand-drawn look that makes for a compelling background image.
startshape scale
rule scale{
shape{s .1 y -.5 x 1}
}
rule shape{
SQUARE{ b 1 s 1.1 }
SQUARE{ a -.5 }
shape{ y 1.5 r 10 s .99}
}
rule shape{
SQUARE{ b 1 s 1.1 }
SQUARE{ }
shape{ y 1.5 r 5 s .99}
}
rule shape .03 {
TRIANGLE{ }
shape{ y 1.5 r 10 s .95 b .1}
shape{ y 1.5 r 10 s .95 flip 90 b .1}
}

A large version of this image is also available. You can also play with this pattern live on Algorithm Ink. And for those who missed it, here’s the ContextFree.js code. Email me, or comment below to get involved.
RT @azaaza ContextFree.js & Algorithm Ink: Making Art with Javascript | Follow @azaaza on Twitter | All blog posts
an0n1 m0us
unless every website wants a paisley kaleidoscope look and feel, this appears nice but irrelevant.
Can SOMEONE show me SOMETHING USEFUL I can do with canvas beyond graphs which we could do in many ways already?
Anon
To the above poster, welcome to a new web that allows artists to create art without needing to know how to program. The kind of abstraction that the author has provided allows you to build complex systems (in this case, works of art) simply. It unshackles creativity from technicality.
I look forward to what will be produced from this!
an0n1 m0us
Why do artists need to create art within the web? There are ample tools and methods for creating art, yet simple fundamental layout elements are still missing from the web!
That a standards-compliant means for programmatically drawing and animating vector art is being developed is a good thing. I’m happy about that because Flash is evil.
However it drives me mad – as a full time browser hacker – to see precious developer resources and political will devoted to this before simplistic layout effect like independent backgrounds per box or border-radius, is supported.
Unfortunately there are a fair few canvas posts coming out right now that simple do not explain it’s scope. Can it be used for simple effects?
JeffG
@an0n1 m0us: you’re forgetting that in open source, there is no single way to direct precious developer resources and that is a good thing. Clearly this is a labor of love for Aza, and if writing it made him happy then I’m all for it.
an0n1 m0us
@jeffG
That is not quite true. Mozilla employs a lot of developers. It was, presumably, Mozilla’s choice to instruct one or several of their paid developers to implement canvas before other features. Certainly it seems Mike Shaver is the one who has final yay/nay on which features get rolled into releases. AFAIK Shaver is paid so I’m not really sure that your point about open source is completely valid.
As for Aza having fun, by all means! The decision to support a non-standard version of canvas in Fx3 was made hundreds of moons ago. It’s there atm so might as well play with this new toy. I’m all for developers being creative and enjoying their code. I just wish the process of what browsers support was more open and not dictated imperialistically by east coast america.
Boriss
Very cool stuff Aza! The same circle recursion fractal took me 20 lines in Processing. I’ll play around with this some more. :)
Ryan Singer
Thanks for creating and sharing this Aza. The UI is fresh and inspiring.
Aza Raskin
@an0n1 m0us: The issue you raise, about settings of priority for implementing back-end features of Firefox, is an important one. The strength of the open source community is its diversity: the seemingly irrelevant bits that an excited hacker makes today makes it possible to implement a core feature tomorrow. That said, I would encourage you to get involved directly in the setting of priorities. The benefit of being an open community is exactly that anyone can have voice. Do you have any specific core features that you’d like to see in Firefox 3.1?
@Ryan and Boriss: Thanks! I’m not yet happy with the UI, but I think it sneaks in under “good enough”.
WAHa.06x36
Is there a way to control recursion depth? I’d really like to be able to tell the thing when to stop, or else it might just ruin a picture with unwanted tiny details.
For instance, manually setting the size limit would be neat for something like http://azarask.in/projects/algorithm-ink/#06b4c332
Aza Raskin
@WAHa.06×36: First, I love that piece. There currently isn’t a way to globally stop designs (although you could add rules so that some of the chains randomly stop). It would not be hard to add such a thing to a background (or similar) rule. Currently, there is a constant which is checked against for limiting the mini-ness of objects, so changing that constant to be read from the Context Free grammar source code is easy.
skierpage
Aza, lovely stuff. It’s great to tweak variables in the source and get wildly different patterns. CFDG only has SQUARE, CIRCLE, TRIANGLE, but could you add other primitives matching canvas, like a LINE primitive?
an0n1 m0us,
If you had paid attention to the blog post you’d know Canvas is a whatwg/HTML5 standard, implemented by all modern browsers except laughable MSIE. The development of new browser features is a combination of feature innovation (which in Mozilla you can watch and contribute) and standards body efforts.
“dictated imperialistically by east coast america”… hah, I’m not aware of any browser development or standards work taking place on the East coast!
WAHa.06x36
@Aza: Thanks! It came to me in flash of insight while making total garbage.
And yeah, I figured it was doing something like that and that making that change should be easy. If you do add it, let us know!
web design
check out his main site, too http://www.contextfreeart.org/ the main site was a programming submission many months ago– stuff like this makes programming worth reading… or wherever it’s supposed to be filed (who knows!?) the update is cool, as well.
Aza Raskin
@web design: To be clear, http://www.contextfreeart.org/ was not created by me — it is a project by the most Mark Lentczner and John Horigan. It is, however, truly awesome.
Jimmy
Is there an API I can look at to see what all these options mean (besides the ones you explained), as well as the possible shapes?
Michael
Aza, “web design” is a spambot. He takes the #1 comment from reddit and reposts it on the blog while linking to some site. Pretty ingenius I must say, but rather annoying.
Jesse Ruderman
Algorithm Ink warns that Safari isn’t “canvas standards complaint”, but it works fine in Safari. Meanwhile, it doesn’t warn about Opera, but Opera draws all circles as diamonds (see e.g. http://azarask.in/projects/algorithm-ink/#bb0f2e8f)
Versions tested: Opera 9.50 and Safari 3.1.2 on Mac OS X 10.4.
Roger Purves
to Aza:
This is a post from a non-programmer, with a proposal for
an alternative to the “Hello, World!” program you mention. But before getting to that, I want to say how much I enjoyed (and agreed with) your introductory remarks.
In the past couple of years, I have occasionally posted and or sent emails promoting the “Hello World!” below as a feeble attempt to get programming languages/environments a little closer to the interface that Apple introduced in the 1984 mac. (I realize that Apple was building on the work done at Xerox Parc, SRI, and others.)
A proposal for a new “Hello, World!”:
………………………………………………………………………..
A window shows a circle, a square, and a text box
displaying:
“Please drag the circle into the square”
(The circle should be outside the square
and be small enough to fit in the square.)
A user kindly complies with this modest
request. As soon as he releases the
mousebutton (after doing the drag), the
text “Hello, World” appears somewhere
in the window.
(I omit matters of quitting the program.)
………………………………………………………………………..
This (for me) is a more transparent equivalent of a “Hello, World” for a graphical environment than a “dot that follows the cursor” program.
Aza, it would not surprise me if a preference here seems
silly to you. You can see, at a mental glance, the code for
both examples; decide that there are no interesting
differences between the two programs (if so), and thus
no point preferring one to the other.
But, as a non-programmer, I cannot envisage the code.
On the surface, I see immediately that the “drag circle
into square” program is a toy version of dragging a
document into the trash, or dragging a tool from a
palette onto a graphical element, and so on—interactions
possible in the 1984 mac (and used in every non-programmers environment since then.) On the other hand, I am unable to make a leap like this from the “dot follows the cursor” example.
You probably have much better things to do than comment on various “Hello, World!” proposals; but, if you have a moment to reply, I am curious to know whether the “drag circle into square” program can be handled in ContextFree.js.
Thank you for not forgetting what it’s like to be a kid.
Roger Purves
PS. I would like to put in a plug for:
http://processing.org/learning/basics/
This page (and the material linked to there) is a great way
to introduce a new programming world to visitors. I wish more people would imitate the format.
Matt Katz
Aza – Love it first time I played with it. Came back to figure out some more and now I’m seeing an infinite redirect. http://azarask.in/projects/algorithm-ink/#52ad0ba6 -> http://azarask.in/blogblogblogblogblogblogblogblogblogblogblogblogblogblogblogblogblogblogblogblogprojects/algorithm-ink/#52ad0ba6
While a hilarious URL, it is not the context free goodness I seek.
Zachery Bir
Infinite recursion trying to just get to Algorithm Ink. Problem with a rewrite rule?
Zachery Bir
Also, “A Peek at the Syntax” and “Improvements”, unless those were subtle, and I was too far above the threshold.
Matt Katz
I like – I ended up taking a few of the examples and embedding them in the header of my own website – doesn’t seem to push Firefox at all to be generating all that art and it looks neat.
Thanks!
dil okulu
is there any information about this in other languages, maybe german or other else?
SS
Hi,
Can you please tell how I can insert this code to a HTML page. Please tell me ASAP
alikos
На самом деле, как говорится – Без пользы жить – безвременная смерть.
Василий
Спасибочки. Это именно то, что всем нужно было :)
Myjcbnuy
good post man thx filestube
%PPP
internetten para kazanma yolları
does anyone knows if there is any other information about this subject in other languages?
Vic Stapel
I have spend just more that ever on your page Algorithm Ink would love to learn more about whats the language one has to learn to write the things. Is it in windows?
I love more the one that repeat by mouse click than the ones one can not control. Thanks its like doodling without paper :-)
TranceParty
Материал правильный, закину сайт в избранное.
Тимур
Как обычно, хозяин сайта весело накреативил.
Аня ранетка
Уважаемый +1
name
7
Zayıflama Lida Fx15 Ve Biber Hapı Zlfvbh
To the above poster, welcome to a new web that allows artists to create art without needing to know how to program. The kind of abstraction that the author has provided allows you to build complex systems (in this case, works of art) simply. It unshackles creativity from technicality.
michael
“It uses Canvas to to the drawing…”
v-pills
Because the controls are accessed by panning, for the most part every single pixel of the screen is filled with what you care about most: the content.
Crazykiwi
I would love to see something like “Making Art with Javascript” customized for people with movement based disabilities. Allowing them to turn a slight finger movement, stylus movement or mouse movement into a beautiful piece of visual artwork.
smok3
is there a chance to save the series of images (like each image is saved to disk during calcs)? I’d like to do some video editing later