Matt Sweetman

Latest articles

An experiment in Processing.js

Fireflies screenshot

Fireflies is a little experiment written in Processing.js. In my previous post I mentioned that some sort of library would make working with the Canvas object easier, well it turns out it already exists.

Processing.js is a javascript implementation of the original Processing library - a graphics programming tool for Java. The javascript version follows a similar syntax to the Java version, meaning it looks quite different from regular javascript. Whether this is a good or bad thing probably depends on the angle you're coming from.

The following code is an example of how Processing.js looks. It's taken from my fireflies experiment, but trimmed down a bit to help focus on the syntax rather than implementation.

<script type="application/processing">
  int WIDTH = 800;
  int HEIGHT = 600;

  class Firefly {
    float x = random(WIDTH);
    float y = random(HEIGHT);
    float ox = x;
    float oy = y;
    float a = random(1);
    float wx;
    float wy;

    Firefly() {
      wx = random( (WIDTH + 100) - 50 );
      wy = random( (HEIGHT + 100) - 50 );
    }

    void draw() {
      int r = max(0, round(255 - p * 2));
      int g = round(p * 2);
      int b = 255;
      stroke(r, g, b, a * 255);
      line(ox, oy, x, y);
    }
  }
</script>

This creates a single firefly particle, which is then instantiated hundreds of times. As you can see it closely resembles Java in its syntax. The code would never execute in a regular javascript engine, but the surrounding <script type="application/processing"> tags give us a clue as to how it's being treated. A regular browser will ignore the contents because of the non-standard type attribute, but Processing.js will pick it up and actually parse it into regular javascript, converting all the necessary Canvas calls in the process.

It produces good results, pretty much indistinguishible from regular javascript in terms of performance. However because the code is translated it generates some really obscure errors if you have a bug. There's no easy way to find out what part of your original code produced the error, which makes the debugging process very much trial-and-error.

There's also some vital information missing from the beginners guide on the Processing.js website. Things are a lot easier if you use the init.js script found in their examples.zip. It took me quite a while to get things set up, so try the following if you're having trouble:

  1. Add the processing.*xx*.min.js in a script tag.
  2. Add init.js in the same manner, which can be found in the examples zip on the Processing.js website.
  3. Ensure your processing script tag and Canvas object are in the same div container, and the script tag is above the canvas.
  4. Be sure to have a setup() method and inside set the canvas size with the size() method