Installation

Download the latest version of gpu.js and include the file in your HTML page using the following tags:

<script src="/path/to/js/gpu.min.js"></script>

In JavaScript, initialise the library:

var gpu = new GPU();

Creating and running functions

Depending on your output type, specify the intended dimensions of your output. You cannot have a accelerated function that does not specify any dimensions.

Dimensions of Output How to specify dimensions
1D [length]
2D [width, height]
3D [width, height, depth]
var opt = {
    dimensions: [100]
};

Create the function you want to run on the GPU. The first input parameter to createKernel is a kernel function which will compute a single number in the output. The thread identifiers, this.thread.x, this.thread.y or this.thread.z will allow you to specify the appropriate behavior of the kernel function at specific positions of the output.

var myFunc = gpu.createKernel(function() {
    return this.thread.x;
}, opt);

The created function is a regular JavaScript function, you can use it like regular functions.

myFunc();
// Result: [0, 1, 2, 3, ... 99]

Note: Instead of creating an object, you can use the chainable shortcut methods as a neater way of specificying options.

var myFunc = gpu.createKernel(function() {
    return this.thread.x;
}).dimensions([100]);
    
myFunc();
// Result: [0, 1, 2, 3, ... 99]

Accepting input

Kernel functions may accept numbers, or 1D, 2D or 3D array of numbers as input. To define an argument, simply add it to the kernel function like regular JavaScript.

var myFunc = gpu.createKernel(function(x) {
    return x;
}).dimensions([100]);
    
myFunc(42);
// Result: [42, 42, 42, 42, ... 42]

Similarly, with array inputs:

var myFunc = gpu.createKernel(function(X) {
    return X[this.thread.x % 3];
}).dimensions([100]);
    
myFunc([1, 2, 3]);
// Result: [1, 2, 3, 1, ... 1 ]

Graphical output

Sometimes, you want to produce a canvas image instead of doing numeric computations. To achieve this, set the graphical flag to true and the output dimensions to [width, height]. The thread identifiers will now refer to the x and y coordinate of the pixel you are producing. Inside your kernel function, use this.color(r,g,b) or this.color(r,g,b,a) to specify the color of the pixel.

For performance reasons, the return value for your function will no longer be anything useful. Instead, to display the image, retrieve the canvas DOM node and insert it into your page.

var render = gpu.createKernel(function() {
    this.color(0, 0, 0, 1);
}).dimensions([20, 20]).graphical(true);
    
render();

var canvas = render.getCanvas();
document.getElementsByTagName('body')[0].appendChild(canvas);

Note: To animate the rendering, use requestAnimationFrame instead of setTimeout for optimal performance. For more information, see this link.