webgl-node
v1.5.1
Published
WebGL2 implementation for Node.js on top of native-gles
Maintainers
Readme
webgl-node
WebGL2 implementation for Node.js, backed by native OpenGL ES via native-gles.
Provides a spec-compliant WebGL2RenderingContext that runs on real GPU hardware through EGL pbuffer contexts. Designed for running browser GL code (like three.js) in Node.js without a browser.
Features
- Full WebGL 2.0 spec compliance — Complete implementation of the WebGL 2.0 specification, including UBOs, transform feedback, sync objects, sampler objects, 3D textures, instanced drawing, multiple render targets, and PBO offsets
- Cross-platform — Works on Linux, macOS, and Windows
- x64 and arm64 — Native support for both architectures on all three platforms
- Real GPU acceleration — Runs directly on the system's OpenGL ES 3.0 driver, no software translation layer
- Minimal footprint — ~1200 lines of JS wrapping a thin native addon; single runtime dependency
Install
npm install webgl-nodeRequires native-gles (EGL/GLES3 bindings for Node.js).
Quick Start
import { createWebGL2Context } from 'webgl-node'
const { canvas, gl } = createWebGL2Context(800, 600)
// Use gl exactly like a browser WebGL2RenderingContext
gl.clearColor(0.2, 0.3, 0.4, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)
// Read pixels back
const pixels = new Uint8Array(800 * 600 * 4)
gl.readPixels(0, 0, 800, 600, gl.RGBA, gl.UNSIGNED_BYTE, pixels)API
createWebGL2Context(width, height, opts?)
Creates an EGL pbuffer context and returns:
canvas— Mock canvas object compatible with libraries that expectcanvas.getContext('webgl2')gl— FullWebGL2RenderingContextinstance.makeCurrent()andctxIdare also set on this object (non-enumerably), because consumers routinely keep onlygland throw the wrapper away -- a library that holdsgland callsgl.makeCurrent?.()before its own GL work needs that call to actually do something. See the multi-context note below for what an unnoticed no-op costs.ctxId— The native-gles context handle backing this contextmakeCurrent()— Make this context current before renderingdestroy()— Destroy this context (and only this one)resize(width, height)— Follow a surface size change.drawingBufferWidth/Heightare cached at creation, so after a window resize (or going fullscreen) they still report the ORIGINAL size, and anything sizing a viewport or a blit from them draws into a rect built for the old window. There is no event to hook — the owner of the window has to say so. Updates the cached size, and resizes the underlying pbuffer when the context is offscreen (a window surface tracks its own window, so native-gles treatsresizeContextas a no-op there).attachWindow(handle)— Bind this context to a native window handle, turning a pbuffer context into one that presents to that window. Returnsfalseif the bind is refused (the context is left untouched and still usable offscreen). On successswapBuffers/setSwapIntervalbecome available even if the context was created without the window opts below.detachWindow()— Release the window surface and return to offscreen rendering. Returnsfalseif not attached.
native-gles is multi-context: each createWebGL2Context call creates an
independent EGL context with its own object namespace, and every returned
function is bound to it. In a process with more than one context (several
carts, a compositor and a cart, …) each consumer must call its own
makeCurrent() before rendering — whoever rendered last owns the current
context otherwise, and draws land in the wrong context silently.
WebGL2RenderingContext
Implements the complete WebGL 2.0 API:
- Buffers:
createBuffer,bindBuffer,bufferData,bufferSubData,copyBufferSubData,getBufferSubData - VAOs:
createVertexArray,bindVertexArray,vertexAttribPointer,vertexAttribIPointer,vertexAttribDivisor - Shaders & Programs:
createShader,compileShader,createProgram,linkProgram,useProgram - Uniforms: All scalar, vector, and matrix variants (
uniform[1234][fiui][v],uniformMatrix[234]x[234]fv) - Textures:
texImage2D/3D,texSubImage2D/3D,texStorage2D/3D,compressedTexImage2D/3D,compressedTexSubImage2D/3D - Framebuffers:
createFramebuffer,blitFramebuffer,framebufferTextureLayer,readBuffer,invalidateFramebuffer - Renderbuffers:
renderbufferStorage,renderbufferStorageMultisample - Drawing:
drawArrays,drawElements,drawArraysInstanced,drawElementsInstanced,drawRangeElements,drawBuffers - Queries:
createQuery,beginQuery,endQuery,getQuery,getQueryParameter - Sync:
fenceSync,clientWaitSync,waitSync,getSyncParameter - Samplers:
createSampler,samplerParameteri/f,getSamplerParameter - Transform Feedback:
createTransformFeedback,beginTransformFeedback,transformFeedbackVaryings - UBOs:
bindBufferBase,bindBufferRange,getUniformBlockIndex,uniformBlockBinding,getActiveUniforms - State:
getParameter,getIndexedParameter,isEnabled,getError - Readback:
readPixels,getBufferSubData - Clear Buffers:
clearBufferfv,clearBufferiv,clearBufferuiv,clearBufferfi - Extensions:
getSupportedExtensions,getExtension
GL (constants)
All WebGL2 constants exported as a plain object:
import { GL } from 'webgl-node'
console.log(GL.TRIANGLES) // 0x0004Constants are also available as properties on the context: gl.TRIANGLES.
WebGL Object Classes
Exported for instanceof checks:
import { WebGLBuffer, WebGLTexture, WebGLProgram, WebGLShader } from 'webgl-node'Mock Canvas
The returned canvas object supports:
width,height,clientWidth,clientHeightgetContext('webgl2')— returns the GL contextgetBoundingClientRect()— returns dimensionsaddEventListener(),removeEventListener()— no-opsstyleobject
This is sufficient for libraries like three.js that probe canvas properties during initialization.
Rendering to a Window with SDL
For on-screen rendering, pair with @kmamal/sdl. Create an SDL window with opengl: true and pass its native GL handle:
import sdl from '@kmamal/sdl'
import { createWebGL2Context } from 'webgl-node'
const win = sdl.video.createWindow({ title: 'My App', width: 800, height: 600, opengl: true })
const { canvas, gl, swapBuffers, makeCurrent } = createWebGL2Context(800, 600, {
nativeWindow: win.native.gl,
})
// Re-assert EGL context after SDL init
if (makeCurrent) makeCurrent()
// Render loop
setInterval(() => {
gl.clearColor(0.2, 0.3, 0.4, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)
swapBuffers()
}, 16)
win.on('close', () => process.exit(0))When nativeWindow (or windowSurface) is provided, createWebGL2Context also returns:
swapBuffers()— present the framesetSwapInterval(n)— set vsync (1 = on, 0 = off). On macOS this drivesCAMetalLayer.displaySyncEnabledthrough native-gles (ANGLE's owneglSwapIntervalis a no-op there).
Object names are integers with no context identity. Two contexts each
allocate texture name 1, 2, 3... independently, and every GL call -- including
glDeleteTextures -- is dispatched against whichever context is current.
So deleting "your" texture 3 while somebody else's context is current
destroys their texture 3. A teardown that means to call makeCurrent()
first and silently does not will corrupt an unrelated context, and the damage
looks like a rendering bug in the victim: a live window went black at a
healthy 60fps (GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT, attachment
GL_NONE) while a CPU readback of that same cart still showed a perfect
picture. This is why makeCurrent is on the context object and not only on
the wrapper.
makeCurrent() and destroy() are returned for every context, window or
pbuffer — see above.
Attaching a window to an existing context
nativeWindow above requires the handle up front. When the context already
exists and a window arrives later — an offscreen renderer that a viewer window
opens onto — use attachWindow(handle) instead:
const ctx = createWebGL2Context(1920, 1080) // offscreen; no window yet
// ... render offscreen, read pixels back, whatever ...
if (ctx.attachWindow(win.native.handle)) { // now present to a real window
ctx.setSwapInterval(0) // see the note below
ctx.swapBuffers()
}
ctx.detachWindow() // back to offscreen renderingThis replaces a glReadPixels + software-blit round trip with a GPU swap. Read
pixels back BEFORE swapping: after a swap the back buffer's contents are
undefined, so a readback then returns a torn or stale frame.
Set
setSwapInterval(0)unless you specifically want to block on vsync. The driver default is 1, which parks the calling thread insideswapBuffers()until the next vblank — measured at ~33 ms/frame, i.e. slower than the CPU round trip you are replacing, and on a single-threaded host it blocks the whole event loop. A window toolkit's own "vsync off" setting does not affect this surface's interval.
On macOS pass win.native.handle (an NSView*); native-gles resolves it to
the view's backing CALayer for ANGLE's Metal backend and keeps its
contentsScale synced to the display the window is on.
See examples/ for complete demos using three.js with SDL.
Notes
- Runs on EGL pbuffer (offscreen) — no window or display required
- Boolean parameters (
depthMask,colorMask,vertexAttribPointernormalized, etc.) are coerced with!!for N-API compatibility - WebGL-specific pixel store params (
UNPACK_FLIP_Y_WEBGL,UNPACK_PREMULTIPLY_ALPHA_WEBGL) are tracked in JS getParameterreturns proper WebGL wrapper objects for binding queriesgetUniformintrospects the uniform type to return the correct typed arraytexImage2DandtexSubImage2Daccept the Image/Canvas source form; pixels are read back via the source'sgetContext('2d')(or a temp canvas for anImage), so the source must expose a 2D context
License
MIT
