TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/Nightre/Rapid.js/llms.txt
Use this file to discover all available pages before exploring further.
Rapid class is the central object that owns the WebGL2 context, manages rendering regions, and exposes all draw methods. Every frame you call clear(), issue draw calls, and the batched geometry is automatically flushed to the GPU. A single Rapid instance maps to a single <canvas> element.
Constructor
Rapid renderer attached to the supplied canvas. The constructor acquires a WebGL2RenderingContext, allocates internal regions, and calls resize() once to establish the initial viewport and projection matrix.
IAppOptions
The target
<canvas> element. Rapid will call getContext("webgl2") on this element and manage its dimensions.Logical coordinate-space width in CSS pixels. Draw calls use this coordinate system. Defaults to
physicsWidth / dpr when omitted.Logical coordinate-space height in CSS pixels. Defaults to
physicsHeight / dpr when omitted.GPU pixel width of the WebGL backbuffer. Defaults to
canvas.clientWidth × devicePixelRatio.GPU pixel height of the WebGL backbuffer. Defaults to
canvas.clientHeight × devicePixelRatio.Default clear color applied by
clear(). Defaults to Color.Black (0, 0, 0, 255).Request MSAA antialiasing from the WebGL context. Default
false. Has no effect after context creation.Default texture sampling filter.
TextureFilterMode.NEAREST (default) preserves hard pixel edges; TextureFilterMode.LINEAR smooths magnified textures.Whether texture data is treated as having premultiplied alpha. When
true (default), the blend equation uses (ONE, ONE_MINUS_SRC_ALPHA) for correct compositing.When
true, vertex positions are snapped to integer pixels before upload, eliminating sub-pixel jitter on pixel-art assets. Default false.Controls how the canvas scales when the CSS size differs from the logical size. See the CanvasScaleMode enum for details. Defaults to
CanvasScaleMode.CanvasItem.Public Properties
| Property | Type | Description |
|---|---|---|
gl | WebGL2RenderingContext | The active WebGL2 context. Use for low-level GL calls. |
canvas | HTMLCanvasElement | The target canvas element passed at construction. |
texture | TextureManager | Manager for creating and caching textures. |
matrixStack | MatrixStack | Hierarchical transform stack. See MatrixStack. |
matrix | MatrixStore | Direct access to the flat matrix buffer. See MatrixStore. |
logicWidth | number | Logical coordinate-space width (CSS pixels). |
logicHeight | number | Logical coordinate-space height (CSS pixels). |
physicsWidth | number | GPU backbuffer width in physical pixels. |
physicsHeight | number | GPU backbuffer height in physical pixels. |
dpr | number | Device pixel ratio (window.devicePixelRatio). |
backgroundColor | Color | Clear color used by clear(). Writable at any time. |
drawcallCount | number | Number of WebGL draw calls issued since the last clear(). Useful for performance profiling. |
width | number | Getter — alias for logicWidth. |
height | number | Getter — alias for logicHeight. |
Frame Lifecycle Methods
Every game loop iteration follows the same three-step pattern: clear the previous frame, issue draw calls, then let Rapid automatically flush or callflush() explicitly.
clear()
backgroundColor, resets drawcallCount to zero, and calls matrixStack.reset() to wipe all saved transform state. Call this at the start of every frame.
flush()
flush() automatically whenever it needs to switch shaders, textures, or blend modes. You only need to call it manually when mixing Rapid draw calls with raw WebGL API code.
resize(logicWidth, logicHeight, cssWidth?, cssHeight?)
cssWidth/cssHeight are provided, the canvas style.width and style.height are updated as well.
New logical width. Draw-call coordinates use this space.
New logical height.
Optional CSS display width. Updates
canvas.style.width and recalculates physicsWidth = cssWidth × dpr.Optional CSS display height.
Settings Methods
setTextureFilter(filter)
TextureFilterMode.NEAREST for hard-edged pixel art; TextureFilterMode.LINEAR for smooth bilinear filtering.setAntialias(antialias)
antialias property on the renderer. Note that the WebGL context’s MSAA setting is fixed at construction time; this property is used by internal rendering logic that reads it at draw time.
true to enable antialiasing; false to disable.Draw Methods
All draw methods accept an options object that extendsITransformOptions, so you can pass transform properties (x, y, rotation, scale, origin, etc.) directly alongside shape-specific properties. See ITransformOptions for the full list.
drawSprite(options)
The texture (or atlas sub-region) to render.
Tint color multiplied with every fragment. Default white (
0xFFFFFFFF).Mirror the sprite horizontally.
Mirror the sprite vertically.
Expands the rendered quad by this many pixels on every side, allowing shader effects (e.g. outlines) to bleed outside the original sprite boundary.
Custom
GLShader or CustomGlShader to override the default sprite shader.drawRect(options)
Rectangle width in logical pixels.
Rectangle height in logical pixels.
Fill color. Defaults to opaque white.
Optional texture stretched over the rectangle.
drawCircle(options)
Circle radius in logical pixels.
Fill color. Defaults to opaque white.
Number of triangles used to approximate the circle. Higher values produce smoother edges at a cost of more vertices. Default
32.drawLine(options)
Array of control points defining the line path. Minimum 2 points required.
Stroke width in logical pixels. Default
1.Stroke color.
When
true, connects the last point back to the first.Adds semicircular caps at both ends of an open polyline.
Texture to map along the line.
STRETCH maps the texture once across the full length; REPEAT tiles it.drawGraphic(options)
Vertices as
Vec2 or {x, y} objects.Uniform tint or per-vertex color array.
WebGL drawing mode constant (e.g.
gl.TRIANGLES, gl.TRIANGLE_FAN). Defaults to gl.TRIANGLES.Per-vertex UV coordinates mapped to
options.texture.Optional texture to sample in the graphic shader.
Low-Level Vertex API
Use these methods when you need direct control over geometry data — for example, to build custom sprite atlases, particle meshes, or procedural shapes that don’t fit the higher-level helpers.Always bracket
addGraphicVertex / addRectVertex / addCircleVertex calls with a matching startGraphic() … endGraphic() pair. Calling them outside that bracket is undefined behaviour.startGraphic(drawMode?, texture?, shader?, customMatrix?)
customMatrix provides a different matrix index from MatrixStore.
WebGL primitive type. Default
gl.TRIANGLES.Texture bound during this batch.
Override shader for this batch.
Index into
MatrixStore to use as the transform. Defaults to matrixStack.curWorldM.startMaskGraphic(drawMode?, texture?, customMatrix?)
addGraphicVertex / addRectVertex / addCircleVertex / endGraphic() when you want to build mask shapes from raw vertices instead of using startDrawMask.
WebGL primitive type. Default
gl.TRIANGLES.Optional texture whose alpha channel may be used to shape the mask.
Index into
MatrixStore to use as the transform. Defaults to matrixStack.curWorldM.addGraphicVertex(x, y, u?, v?, color?)
X coordinate in local space.
Y coordinate in local space.
U texture coordinate (0–1). Default
0.V texture coordinate (0–1). Default
0.32-bit ABGR vertex color. Default
0xFFFFFFFF (opaque white).addRectVertex(w, h, color?)
(0, 0) to (w, h) with UV coordinates mapped to (0,0)–(1,1). Intended for use with gl.TRIANGLE_FAN.
addCircleVertex(r, color?, segments?)
segments vertices arranged around the origin at radius r. Use with gl.TRIANGLE_FAN alongside a centre vertex at (0, 0, 0.5, 0.5). Default segments is 32.
endGraphic()
Render Texture Methods
Render textures let you draw into an off-screen framebuffer and then use the result as a texture in subsequent draw calls. This is the foundation for post-processing, cached layers, and multi-pass effects.enterRenderTexture(rt)
rt as the active render target, flushes any pending draw calls, and updates the viewport and projection to match the render texture dimensions. All subsequent draw calls go into rt until leaveRenderTexture() is called.
leaveRenderTexture()
drawToRenderTexture(rt, cb, color?)
cb, and then leaves the render texture — even if cb throws.
The target render texture.
Draw calls to execute inside the render texture.
Clear color before executing
cb. Pass null to skip clearing and composite on top of existing RT contents. Defaults to transparent black (0, 0, 0, 0).clearRenderTexture(color?)
color. Defaults to transparent black. Must be called while a render texture is active (i.e. inside an enterRenderTexture / leaveRenderTexture block).
applyFilters(source, shaders)
source using an internal ping-pong pair of render textures. Each shader receives the output of the previous one as its input texture. The two internal render textures are reused across calls (resized on demand). The returned RenderTexture is valid until the next applyFilters call.
The input texture to start the filter chain from.
Ordered array of shaders to apply. Must not be empty.
The render texture containing the final filtered result. Render it with
drawSprite to display on screen.Convenience Wrappers
These methods bundle a common setup / teardown pattern into a single call, usingtry / finally to guarantee cleanup even if the callback throws.
withTransform(cb, transform?, width?, height?)
cb, then restores. When transform is omitted a bare save/restore wraps the callback. When transform.saveTransform is false the save step is skipped.
Draw calls to execute within the transform.
Transform options (position, rotation, scale, origin, …).
Logical width passed to origin anchor resolution. Default
0.Logical height passed to origin anchor resolution. Default
0.withBlendMode(mode, cb)
mode, runs cb, then restores BlendMode.NORMAL.
withMask(maskCb, drawCb, type?, ref?)
maskCb into the stencil buffer (invisible to the colour buffer), then draws drawCb clipped to the stencil region.
Geometry that defines the mask shape.
Draw calls rendered within the mask.
MaskType.EQUAL renders inside the mask (default); MaskType.NOT_EQUAL renders outside it.Stencil reference value. Default
1.withScissor(x, y, w, h, cb)
cb, then disables scissoring.
Mask / Stencil Methods
For finer-grained control over multi-layer stencil masks, use the low-level methods directly.startDrawMask(ref?, mask?)
ref into the stencil.
Stencil write value. Default
1.Stencil bitmask. Default
0xFF.endDrawMask()
clearMask(mask?)
0xFF clears all stencil layers.
enterMask(type, ref?, mask?)
startDrawMask.
EQUAL draws inside; NOT_EQUAL draws outside.Reference value to test against. Default
1.Bitmask. Default
0xFF.exitMask()
ALWAYS pass).
drawMaskImage(options)
options.texture into the stencil buffer as a mask rectangle using the texture’s alpha channel.
Texture whose alpha drives the mask shape.
Blend Mode Methods
setBlendMode(mode)
blendFuncSeparate for the requested mode. The alpha channel is handled separately from RGB to avoid darkening artifacts on off-screen render textures.
Scissor Methods
startScissor(x, y, width, height)
endScissor()
Region Method
enterRegion(region, customShader?)
Region, flushing any pending draw calls for the previous region first. If the same region and shader are already active, the call is a no-op. This is a low-level method used internally by all draw helpers; call it directly only when building custom region integrations.
The rendering region to activate (e.g.
rapid.spriteRegion, rapid.graphicRegion).Optional shader override for the activated region.
Camera / Coordinate Utilities
renderCamera(transform)
transform to the current matrix and then inverts it in-place, effectively implementing a 2D camera: moving the camera right translates all objects left, and so on.
logicToPhysics(p)
physicsToLogic(p)
cssToDevicePixel(p)
devicePixelToCss(p)
Enums
BlendMode
Controls how incoming (source) fragments are composited with the existing (destination) colour.| Value | Description |
|---|---|
BlendMode.NORMAL | Standard alpha blending. Suitable for most sprites and UI. |
BlendMode.ADD | Additive blending — RGB values are summed. Ideal for glows, fire, and energy effects. |
BlendMode.MULTIPLY | Multiplies source and destination colours. Creates shadows and darkening effects. |
BlendMode.SCREEN | Inverts, multiplies, then inverts again. Softer additive look, avoids harsh white burn-out. |
BlendMode.ERASE | Subtracts source alpha from the destination. Useful for punch-through transparency in render textures. |
MaskType
Determines which pixels survive the stencil test.| Value | Description |
|---|---|
MaskType.EQUAL | Only pixels where stencil equals the reference value are drawn (render inside the mask). |
MaskType.NOT_EQUAL | Only pixels where stencil does not equal the reference value are drawn (render outside the mask). |
TextureFilterMode
Default sampling filter applied to textures uploaded throughTextureManager.
| Value | Description |
|---|---|
TextureFilterMode.NEAREST | Nearest-neighbour filtering. Preserves hard pixel edges; recommended for pixel art. |
TextureFilterMode.LINEAR | Bilinear filtering. Smooths magnified textures; better for high-resolution artwork. |
CanvasScaleMode
Determines how the WebGL backbuffer relates to the CSS display size.| Value | Description |
|---|---|
CanvasScaleMode.CanvasItem | The backbuffer matches the physical screen resolution (logicSize × dpr). Rotated sprites and lines are rasterised at full display resolution for maximum sharpness. |
CanvasScaleMode.Viewport | The backbuffer stays at the logical game size; the browser scales the canvas bitmap to fill the CSS size. Preserves pixel-art aesthetics and avoids extra fragment processing during scale-up. |