package
WebGL2 implementation for Node.js on top of native-gles
npm install webgl-nodeGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 8 packages.
3.6 MB
Includes dependencies.
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.
npm install webgl-nodeRequires native-gles (EGL/GLES3 bindings for Node.js).
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)createWebGL2Context(width, height, opts?)Creates an EGL pbuffer context and returns:
canvas — Mock canvas object compatible with libraries that expect canvas.getContext('webgl2')gl — Full WebGL2RenderingContext instance. makeCurrent() and
ctxId are also set on this object (non-enumerably), because consumers
routinely keep only gl and throw the wrapper away -- a library that holds
gl and calls gl.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
/Height are 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 treats
resizeContext as 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. Returns false if
the bind is refused (the context is left untouched and still usable
offscreen). On success swapBuffers/setSwapInterval become available even
if the context was created without the window opts below.detachWindow() — Release the window surface and return to offscreen
rendering. Returns false if 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.
WebGL2RenderingContextImplements the complete WebGL 2.0 API:
createBuffer, bindBuffer, bufferData, bufferSubData, copyBufferSubData, getBufferSubDatacreateVertexArray, bindVertexArray, vertexAttribPointer, vertexAttribIPointer, vertexAttribDivisorcreateShader, compileShader, createProgram, linkProgram, useProgramuniform[1234][fiui][v], uniformMatrix[234]x[234]fv)texImage2D/3D, texSubImage2D/3D, texStorage2D/3D, compressedTexImage2D/3D, compressedTexSubImage2D/3DcreateFramebuffer, blitFramebuffer, framebufferTextureLayer, readBuffer, invalidateFramebufferrenderbufferStorage, renderbufferStorageMultisampledrawArrays, drawElements, drawArraysInstanced, drawElementsInstanced, drawRangeElements, drawBufferscreateQuery, beginQuery, endQuery, getQuery, getQueryParameterfenceSync, clientWaitSync, waitSync, getSyncParametercreateSampler, samplerParameteri/f, getSamplerParametercreateTransformFeedback, beginTransformFeedback, transformFeedbackVaryingsGL (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.
Exported for instanceof checks:
import { WebGLBuffer, WebGLTexture, WebGLProgram, WebGLShader } from 'webgl-node'The returned canvas object supports:
width, height, clientWidth, clientHeightgetContext('webgl2') — returns the GL contextgetBoundingClientRect() — returns dimensionsaddEventListener(), removeEventListener() — no-opsstyle objectThis is sufficient for libraries like three.js that probe canvas properties during initialization.
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)
When nativeWindow (or windowSurface) is provided, createWebGL2Context also returns:
swapBuffers() — present the framesetSwapInterval(n) — set vsync (1 = on, 0 = off). On macOS this drives
CAMetalLayer.displaySyncEnabled through native-gles (ANGLE's own
eglSwapInterval is 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.
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.
depthMask, colorMask, vertexAttribPointer normalized, etc.) are coerced with !! for N-API compatibilityUNPACK_FLIP_Y_WEBGL, UNPACK_PREMULTIPLY_ALPHA_WEBGL) are tracked in JSgetParameter returns proper WebGL wrapper objects for binding queriesgetUniform introspects the uniform type to return the correct typed arraytexImage2D and texSubImage2D accept the Image/Canvas source form; pixels are read back via the source's getContext('2d') (or a temp canvas for an Image), so the source must expose a 2D contextresize() and after attachWindow(), with your GL state saved and restored around it. Without it a depth-tested draw into a default framebuffer you never cleared fails at random on some GPUspreserveDrawingBuffer: false), the drawing buffer is not cleared after each frame: it keeps its contents, and getContextAttributes() reports preserveDrawingBuffer: true. A program that draws to the canvas without clearing depth sees the previous frame's depth where a browser would see a fresh buffer. Clear the buffers you depend on at the start of each frameMIT
bindBufferBasebindBufferRangegetUniformBlockIndexuniformBlockBindinggetActiveUniformsgetParameter, getIndexedParameter, isEnabled, getErrorreadPixels, getBufferSubDataclearBufferfv, clearBufferiv, clearBufferuiv, clearBufferfigetSupportedExtensions, getExtension. Compressed-texture extensions are advertised when the driver has them (WEBGL_compressed_texture_s3tc, _s3tc_srgb, EXT_texture_compression_bptc, EXT_texture_compression_rgtc, WEBGL_compressed_texture_astc) and WEBGL_compressed_texture_etc always (ETC2 is core in GLES 3.0); getExtension returns each one's format constants, and compressedTexImage2D/3D and compressedTexSubImage2D/3D upload typed arrays (with srcOffset / srcLengthOverride).