a port of the Processing Visualization Language

Processing.js Quick Start - JavaScript Developer Edition

Introduction

This quick start guide is written from the standpoint of a JavaScript developer. The document assumes you know JavaScript and web programming, but only very basic Processing knowledge is assumed.

Index

  1. For the Impatient
  2. Why Processing.js?
    1. What is Processing?
    2. What does Processing bring to the web?
    3. How much work is it to learn Processing?
  3. Ways to use Processing.js
    1. Writing Pure Processing Code
    2. Pre-compiling Processing code to JavaScript
    3. Writing JavaScript-only Processing.js code
    4. Writing Documents that Combine Processing and JavaScript Code
      1. Accessing JavaScript Objects from Processing
      2. Mixing JavaScript and Processing
      3. Accessing Processing from JavaScript
  4. Things to Know as a JavaScript Developer using Processing.js
    1. Processing.js provides access to various DOM/JavaScript objects via the externals property
    2. Division which is expected to produce an integer might need explicit casting
    3. JavaScript, and as such Processing.js, has no "char" datatype
    4. Processing.js has to cheat to simulate Processing's synchronous I/O
    5. Processing.js requires more care with variable naming than Processing
    6. Processing.js needs your help when overriding overloaded superclass methods
    7. It is possible to put Processing code directly in your web page

For the Impatient

If you're in a rush, here's what you need to know:

  1. Processing.js converts Processing code to JavaScript and runs it in the browser, using <canvas> for a drawing surface.
  2. To use it, download Processing.js here: downloads
  3. Make your Processing *.pde files as you normally would, for example hello-web.pde
  4. Create a web page that includes Processing.js as well as a <canvas> with info about where to get your sketch file (you can specify multiple *.pde files, separating them with spaces):
1 <script src="processing-1.3.6.min.js"></script>
2 <canvas data-processing-sources="hello-web.pde"></canvas>

Load your web page, and it will parse, translate, and run your sketch in the browser.

Why Processing.js?

What is Processing?

The Processing language was originally created at MIT as part of the Media lab and Aesthetics and Computation group. They needed a way to bridge the gap between software developers, artists, data visualizers, etc., and to do so in a way that allowed new programmers (or non-programmers) to do complex visual work easily. Processing was built using Java, and can be thought of as a simplified Java, with a simplified Java API for drawing and graphics.

What does Processing bring to the web?

Processing has a large and vibrant community, who are good at creating 2D and 3D graphics, visualizing data sets, audio, video, etc. With HTML5 the web gained canvas, audio, and video--things which had previously only been available via plugins like Flash or Java. At the same time, advances in JavaScript engines have made it possible to do things in script that were previously too slow.

By porting the Processing language to the web, both the Processing and web communities benefit. For Processing, this means that code which used to only work on the desktop now "just works" in the browser. For the web, this means that a new but mature and full-featured approach to graphics programming becomes available. The <canvas> element is too low-level for most developers to use directly--JavaScript libraries are necessary. Processing.js can be thought of as just such a library, simplifying the use of the 2D and 3D canvas operations.

How much work is it to learn Processing?

The Processing language was designed to be small but complete, and easy to learn. This document does not attempt to teach you Processing, and you are encouraged to seek out Processing specific tutorials, books, and examples. Any Processing code or concepts should map to Processing.js (the exceptions are listed below). You can also use pure JavaScript to work with the Processing drawing API, skipping the Java syntax of Processing in favour of JavaScript.

Ways to Use Processing.js

Processing.js was originally created in order to allow existing Processing developers and existing Processing code (often referred to as sketches) to work unmodified on the web. As a result, the recommend way to use Processing.js is to write Processing code, and have Processing.js convert it to JavaScript before running it.

Over time, many web developers have begun using Processing.js, and asked that we design a way for the API to be used separate from the Processing language itself. Therefore, we have provided a way for JavaScript developers to write pure JavaScript code and still use the Processing.js functions and objects. NOTE: Processing.js is first and foremost a port of Processing to the open web, with design decisions favouring compatibility with Processing. It was not designed as a general purpose HTML drawing library. Having said that, it can be used as a high-level drawing API for canvas.

Below we discuss the various methods for using Processing.js in your web pages.

Writing Pure Processing Code

This is the preferred method for using Processing.js, and has been dealt with at length in the Processing.js for Processing Devs quick start guide. To summarize:

  1. Download Processing.js from here
  2. Create a separate Processing file or files, naming them whatever you want, as long as they have a *.pde extension.
  3. Create a web page that includes Processing.js as well as a <canvas> with info about where to get your sketch file(s), and include Processing filenames as a space-separated list in a data-processing-sources attribute on the canvas:
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <title>Hello Web - Processing.js Test</title>
 5   <script src="processing-1.3.6.min.js"></script>
 6 </head>
 7 <body>
 8   <h1>Processing.js Test</h1>
 9   <p>This is my first Processing.js web-based sketch:</p>
10   <canvas data-processing-sources="hello-web.pde"></canvas>
11 </body>
12 </html>

Processing.js will automatically scan the document on page load for <canvas> elements with data-processing-sources attributes, download the files using XMLHTTPRequest, and feed them to the Processing-to-JavaScript translator. The resulting JavaScript is run using eval.

Pre-compiling Processing code to JavaScript

Processing.js automatically downloads and converts any Processing code to JavaScript. It does this using the Processing.compile() method, and those interested in building tools or utilities for Processing.js can do the same.

In order to obtain "compiled" code (i.e., JavaScript suitable for use by the Processing.js runtime) from Processing code, do the following:

1 // hard-coded Processing code, text from an HTML widget, downloaded text, etc.
2 var processingCode = "...";
3 var jsCode = Processing.compile(processingCode).sourceCode;

For example, converting the following Processing code produces the "compiled" JavaScript underneath:

 1 // Processing code
 2 void setup() {
 3   size(200, 200);
 4   background(100);
 5   stroke(255);
 6   ellipse(50, 50, 25, 25);
 7   println("hello web!");
 8 }
 9 
10 // "Comiled" JavaScript code
11 // this code was autogenerated from PJS
12 (function(processing, $constants) {
13   function setup() {
14     processing.size(200, 200);
15     processing.background(100);
16     processing.stroke(255);
17     processing.ellipse(50, 50, 25, 25);
18     processing.println("hello web!");
19   }
20   processing.setup = setup;
21 })

Writing JavaScript-only Processing.js code

The previous method produced JavaScript code from Processing, but you can also write JavaScript on its own. The Processing.js parser turns Processing code into a JavaScript function, then runs it. As a result, it's possible to skip the Processing code altogether, and simply write a JavaScript function, passing this to your Processing instance. Here's an example:

 1 function sketchProc(processing) {
 2   // Override draw function, by default it will be called 60 times per second
 3   processing.draw = function() {
 4     // determine center and max clock arm length
 5     var centerX = processing.width / 2, centerY = processing.height / 2;
 6     var maxArmLength = Math.min(centerX, centerY);
 7 
 8     function drawArm(position, lengthScale, weight) {
 9       processing.strokeWeight(weight);
10       processing.line(centerX, centerY,
11         centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
12         centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
13     }
14 
15     // erase background
16     processing.background(224);
17 
18     var now = new Date();
19 
20     // Moving hours arm by small increments
21     var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
22     drawArm(hoursPosition, 0.5, 5);
23 
24     // Moving minutes arm by small increments
25     var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
26     drawArm(minutesPosition, 0.80, 3);
27 
28     // Moving hour arm by second increments
29     var secondsPosition = now.getSeconds() / 60;
30     drawArm(secondsPosition, 0.90, 1);
31   };
32 }
33 
34 var canvas = document.getElementById("canvas1");
35 // attaching the sketchProc function to the canvas
36 var processingInstance = new Processing(canvas, sketchProc);

Here a sketch function is created, similar to what the parser would produce. This function should take 1 argument, a reference to a processing object (i.e., the Processing runtime), which will be created by the Processing constructor. Any Processing functions or objects are accessible as properties of this object.

Once that function is complete, pass it, along with a reference to a canvas, to the Processing constructor (remember to use new).

Writing Documents that Combine Processing and JavaScript Code

One of the first questions people ask with Processing.js is whether they can read values from the document in which the Processing sketch is running, or vice versa. The answer is yes.

Processing.js converts Processing code into JavaScript contained in a function closure. The variables and functions you create are not attached to the global object (i.e., window). However, you can still get access to them.

Accessing JavaScript Objects from Processing

Since Processing code gets converted to JavaScript and run like any other function, all Processing code has access to the global object. This means that if you create a variable or function in a global script block, they are automatically accessible to Processing. Consider this example:

First the Processing file, mixing.pde:

1 String processingString = "Hello from Processing!";
2 
3 void setup() {
4   printMessage(jsString + " " + processingString);
5 }

Next the web page:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>Hello Web - Accessing JavaScript from Processing</title>
 5     <script src="processing-1.3.6.min.js"></script>
 6 </head>
 7 <body>
 8     <div id="msg">
 9     </div>
10     <canvas data-processing-sources="mixing.pde"></canvas>
11     <script type="application/javascript">
12         var jsString = "Hello from JavaScript!";
13         var printMessage = function (msg) {
14             document.getElementById('msg').innerHTML = "Message: " + msg;
15         };
16     </script>
17 </body>
18 </html>

Here Processing.js allows the use of a variable and function declared outside the Processing code.

Mixing JavaScript and Processing

The previous example kept a clean separation between the JavaScript and Processing code, while loosening the boundary between the two. Because Processing.js converts Processing code to JavaScript, it's also possible to mix them directly. The Processing.js parser will leave JavaScript it finds within the Processing code unaltered, allowing developers to write a hybrid of Processing and JavaScript (NOTE: this is why we don't use a pure Processing parser approach in processing.js). Here is the previous example rewritten using this method:

 1 var jsString = "Hello from JavaScript!";
 2 var printMessage = function(msg) {
 3   document.getElementById('msg').innerHTML = "Message: " + msg;
 4 };
 5 
 6 String processingString = "Hello from Processing!";
 7 
 8 void setup() {
 9   printMessage(jsString + " " + processingString);
10 }

There is some JavaScript syntax that can't be easily mixed this way (e.g., regex literals). In those cases you can simply move your pure JavaScript to a <script> block and access it using the method described above.

Accessing Processing from JavaScript

Reaching out from the Processing code to JavaScript is easier than going the other way, since the JavaScript created by the Processing.js parser is not exposed directly on the global object. Instead, you gain access using the Processing.instances property.

The Processing constructor keeps track of instances it creates, and makes them available using the getInstanceById() method. By default, when a <canvas> has a data-processing-sources attribute, its id is used as a unique identifier for the Processing instance. If no id attribute is provided, you can use Processing.instances[0].

After you have a reference to the appropriate Processing instance, you can call into it like so:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>Hello Web - Controlling Processing from JavaScript</title>
 5     <script src="processing-1.3.6.min.js"></script>
 6 </head>
 7 <body>
 8     <canvas id="sketch" data-processing-sources="controlling.pde"></canvas>
 9     <button onclick="startSketch();">
10         Start</button>
11     <button onclick="stopSketch();">
12         Stop</button>
13     <script type="application/javascript">
14         var processingInstance;
15 
16         function startSketch() {
17             switchSketchState(true);
18         }
19 
20         function stopSketch() {
21             switchSketchState(false);
22         }
23 
24         function switchSketchState(on) {
25             if (!processingInstance) {
26                 processingInstance = Processing.getInstanceById('sketch');
27             }
28 
29             if (on) {
30                 processingInstance.loop();  // call Processing loop() function
31             } else {
32                 processingInstance.noLoop(); // stop animation, call noLoop()
33             }
34         }
35     </script>
36 </body>
37 </html>

Here two buttons in the DOM are used to allow the user to start or stop a running Processing sketch. They control the Processing instance (you might have several in a page, or hidden in divs) directly from JavaScript, calling Processing functions: loop() and noLoop(). The Processing functions are well documented elsewhere.

Things to Know as a JavaScript Developer using Processing.js

While Processing.js tries to be fully compatible with Processing, there are some things which are different or require workarounds. We have also added some web-specific features to make Processing.js easier to use. Here are some tricks and tips as you start working on more complex sketches in Processing.js.

Processing.js provides access to various DOM/JavaScript objects via the externals property

Each Processing instance (i.e., Processing.instances) has an externals property, which is an object containing references to various non-Processing DOM/JavaScript objects that can be useful. For example:

  • canvas - the canvas to which the sketch is bound
  • context - the canvas' context
  • onblur and onfocus - event handlers

Division which is expected to produce an integer might need explicit casting

There are a class of bugs that arise when converting Processing code to Processing.js that involve integer vs. floating point division. What was straight-up integer division in Processing code, when converted to Processing.js, can sometimes become problematic, as numbers become doubles, and introduce a fractional part. The fix is to explicitly cast any division to an integer that exhibits this behaviour:

1 // before
2 int g = mouseX / i;
3 
4 // after
5 int g = (int)(mouseX / i);

See lighthouse bug

JavaScript, and as such Processing.js, has no "char" datatype

JavaScript only knows about numbers, and strings, unlike Java, which also knows about "char" data types. The char is a 16 bit unsigned integer value, that can also pretend to be a letter (from the ISO8859-1 codepage for the first 256 numbers, and basically magic after that). Unfortunately, as JavaScript has no equivalent, relying on char comparisons to be either numbers or letters is quite likely to cause problems. If you have Processing code where you're comparing chars, you will either have to perform int casting, or string casting, using the int() and str() functions, so that you know you're explicitly comparing datatypes that JavaScript can deal with.

Processing.js has to cheat to simulate Processing's synchronous I/O

Processing uses a synchronous I/O model, which means that functions like loadImage() take time to execute, and while they are running, nothing else happens: the program waits until loadImage() is done before moving on to the next statement. This means that you can count on the value returned by a function like loadImage() being usable in the next line of code.

Web browsers don't work like this. The web uses an asynchronous I/O model, which means that functions which load external resources can't make the program wait until they finish. In order to replicate Processing's load* functions, you have to use a special Processing.js Directive.

The Processing.js Directives are hints to the browser that are written in comments rather than in the Processing code itself. Here's a typical Processing sketch that loads an image synchronously and then draws it:

1 PImage img;
2 
3 void setup() {
4   img = loadImage("picture.jpg");
5   image(img, 0, 0);
6 }

This code will not work in the browser with Processing.js, because the call to image() will happen before the file picture.jpg has been downloaded. The fix is to ask Processing.js to download the image before the sketch starts, and cache it--a technique known as preloading. Here is the modified code:

1 /* @pjs preload="picture.jpg"; */
2 PImage img;
3 
4 void setup() {
5   img = loadImage("picture.jpg");
6   image(img, 0, 0);
7 }

Notice the extra comment line at the top of the code. The @pjs directive is for Processing.js, and not the developer. Think of it as an extra line of code that will be executed before the program begins.

If you have multiple images to load, use a list like so:

1 /* @pjs preload="picture.jpg,picture2.jpg,picture3.png"; */

Processing.js requires more care with variable naming than Processing

One of the powerful features of JavaScript is its dynamic, typeless nature. Where typed languages like Java, and therefore Processing, can reuse names without fear of ambiguity (e.g., method overloading), Processing.js cannot. Without getting into the inner-workings of JavaScript, the best advice for Processing developers is to not use function/class/etc. names from Processing as variable names. For example, a variable named line might seem reasonable, but it will cause issues with the similarly named line() function built-into Processing and Processing.js.

Processing.js needs your help when overriding overloaded superclass methods

If your code uses subclasses that override one or more overloaded methods in the superclass, you will need "dummy" overrides for every method signature that you'd normally leave untouched:

 1 class X
 2 {
 3   void doSomething()
 4   {
 5     ...
 6   }
 7 
 8   void doSomething(float x, float y)
 9   {
10     ...
11   }
12 }
13 
14 class Y extends X
15 {
16   void doSomething()
17   {
18     // different code from compared to the super class
19   }
20 
21   // even though we don't override this method,
22   // its signature must be added to prevent Pjs
23   // from getting the method chain wrong:
24   void doSomething(float x, float y)
25   {
26     super.doSomething(x,y);
27   }
28 }

Even though in Processing you will not need to implement the fallthrough method for doSomethign with a (float,float) signature, doing so is almost always necessary to make sure Processing.js doesn't get confused about which class's method to call.

It is possible to put Processing code directly in your web page

Using the data-processing-sources attribute on the canvas, and having Processing.js load an external file is the preferred and recommended way to include scripts in a web page. However, it is also possible to write in-line Processing code.

A few changes are necessary to make the example above work with inline Processing code:

 1 <script src="processing-1.3.6.min.js"></script>
 2 <script type="application/processing" data-processing-target="pjs">
 3 void setup() {
 4   size(200, 200);
 5   background(100);
 6   stroke(255);
 7   ellipse(50, 50, 25, 25);
 8   println('hello web!');
 9 }
10 </script>
11 <canvas id="pjs"> </canvas>

This code is more complex because it has to figure out which canvas goes with which script (i.e., you can have multiple Processing sketches living in the same page, and therefore, multiple canvases). Also note that the scripts include a type attribute, which distinguishes between JavaScript and Processing code (the browser will ignore Processing scripts). Finally, note the use of the id and target attributes to connect the Processing script with the associated canvas.

Fork me on GitHub