How to embed a Processing sketch onto an HTML page

With the release of ProcessingJS it has become relatively easy to share your Processing programs on the web. The process works by compiling your Java code into JavaScript and then rendering the output using the HTML5 canvas element in the browser. The result is a web-based version of your sketch that is rendered without any plugins -- this means that your program will be accessible in any modern browser, including on mobile devices!

Before you start: Preparing your source code

If you've been working in Eclipse you have to make some minor adjustments to your Processing source code before you can render it on the web. Here's how to get started:

Here's a sample of what your code should look like

Now we can embed the code into a web page by doing the following:

Here's a live example (click and hold your mouse to release some colored balls)

If you are planning on using external artwork you will need to upload your assets to your website along with your PDE source code file. Then add the following "preloader" directive at the top of your sketch as a comment - this will tell ProcessingJS to have the files available when your sketch begins running.

/* @pjs preload="file1.png","file2.png","file3.jgp"; */