13 Aug 2010

Using Processing-js as an JavaScript-library

I've started playing with the JavaScript library Processing-js ((Processing-js website)) for rendering in the HTML5 canvas.

Processing ((Wikipedia article)) is a programming language and processing-js is a javascript implementation of that language.
Well, I like JavaScript the way it is and the processing syntax is lazily translated to JavaScript anyway, so I wanted to use it as a normal JavaScript-library, but it wasn't well documented and the only blog post I could find was out-dated.

After spending quite a long time on, which included reading a lot of Processing-js' source code, I found a way to do this ((With version 0.9.6 which is currently the latest release)).

It's actually straight forward, create a new Processing-object and make sure you give it to parameters;

  1. The DOM-canvas element or the ID of the element
  2. a function-reference, this function gets the Processing-object p parsed to it. ((This should have been optional, but without it Processing doesn't initiate properly.))
         var p = new Processing( document.getElementById( "canvas_id" ),

         function( p, c ) {
             p.setup = function( ) {
                 p.size( 1250, 250 );
                 p.background( 55 );
                 p.frameRate( 10 );
                 p.cursor( c.HAND );
             };

             p.draw = function( ) {
                 p.background( 155 );
             };

             Processing.addInstance( p );
         } );

Constants that would be seen as global in the processing language is bound to the c-object argument in my callback function. This is changed behavior in 0.9.7, in 0.9.6 they are bound to the p-object. ((If this isn't clear drop me a comment and I'll try to explain better.))

Functions and variables that would normally be seen as being global in the processing-syntax in actually bound to the p-object and can be referred to directly through p with a few exceptions:

frameRate, mousePressed and keyPressed are both booleans and functions in the Processing-language and we must refer to the boolean version with the prefix __ like this:
p.__frameRate


Tags:


Click to share