GPU.js Constructor Configuration Options Guide
This guide provides an overview of the configuration options
available when instantiating the GPU.js library. By passing an options
object to the GPU constructor
(new GPU(options)), developers can fine-tune rendering
contexts, select specific execution modes, and control platform-specific
drivers for both browser and Node.js environments.
The Constructor Options Object
When creating a new instance via new GPU([options]), the
constructor accepts an optional configuration object. The available
properties are:
1. mode
- Type:
String - Default: Automatically detected (prioritizes
'gpu', falling back to'cpu') - Possible Values:
'gpu','cpu','webgl','webgl2','headlessgl' - Description: Forces GPU.js to use a specific
computation backend. Setting this to
'cpu'forces pure JavaScript execution without hardware acceleration, which is useful for debugging. Setting it to'webgl'or'webgl2'forces that specific graphics API, while'headlessgl'enables server-side GPU execution in Node.js environments.
2. canvas
- Type:
HTMLCanvasElement|OffscreenCanvas - Default:
null(GPU.js creates an internal canvas if needed) - Description: Allows you to supply an existing HTML5
<canvas>orOffscreenCanvaselement for the instance to use. This is particularly useful when you want to render the computation output directly to the screen or integrate with an existing WebGL animation pipeline.
3. context
- Type:
WebGLRenderingContext|WebGL2RenderingContext - Default:
null - Description: An existing WebGL context to be reused by GPU.js. If you are integrating GPU.js into a project that already manages its own WebGL lifecycle (such as Three.js or Babylon.js), passing that context prevents GPU.js from allocating an additional, redundant WebGL context.
4. webGL
- Type:
WebGLRenderingContext| Object - Default:
null - Description: Allows explicitly defining a custom WebGL 1 context or binding custom WebGL implementations.
5. webGL2
- Type:
WebGL2RenderingContext| Object - Default:
null - Description: Allows explicitly defining a custom WebGL 2 context or binding custom WebGL 2 implementations.
6. headlessGL
- Type: Object (the
glmodule in Node.js) - Default:
null - Description: Required when running GPU-accelerated
code on Node.js using headless WebGL. You pass the imported
glpackage (require('gl')) into this property so GPU.js can instantiate an offscreen graphics context in a server environment.
Example Usage
// Browser configuration using WebGL2 and a custom canvas
const myCanvas = document.getElementById('output-canvas');
const gpu = new GPU({
mode: 'webgl2',
canvas: myCanvas
});
// Node.js configuration using headless-gl
const gl = require('gl');
const serverGpu = new GPU({
mode: 'headlessgl',
headlessGL: gl
});