Skip to main content

Documentation 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.

The 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

new Rapid(options: IAppOptions)
Creates a new 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

canvas
HTMLCanvasElement
required
The target <canvas> element. Rapid will call getContext("webgl2") on this element and manage its dimensions.
logicWidth
number
Logical coordinate-space width in CSS pixels. Draw calls use this coordinate system. Defaults to physicsWidth / dpr when omitted.
logicHeight
number
Logical coordinate-space height in CSS pixels. Defaults to physicsHeight / dpr when omitted.
physicsWidth
number
GPU pixel width of the WebGL backbuffer. Defaults to canvas.clientWidth × devicePixelRatio.
physicsHeight
number
GPU pixel height of the WebGL backbuffer. Defaults to canvas.clientHeight × devicePixelRatio.
backgroundColor
Color
Default clear color applied by clear(). Defaults to Color.Black (0, 0, 0, 255).
antialias
boolean
Request MSAA antialiasing from the WebGL context. Default false. Has no effect after context creation.
textureFilter
TextureFilterMode
Default texture sampling filter. TextureFilterMode.NEAREST (default) preserves hard pixel edges; TextureFilterMode.LINEAR smooths magnified textures.
premultipliedAlpha
boolean
Whether texture data is treated as having premultiplied alpha. When true (default), the blend equation uses (ONE, ONE_MINUS_SRC_ALPHA) for correct compositing.
roundPixels
boolean
When true, vertex positions are snapped to integer pixels before upload, eliminating sub-pixel jitter on pixel-art assets. Default false.
scaleMode
CanvasScaleMode
Controls how the canvas scales when the CSS size differs from the logical size. See the CanvasScaleMode enum for details. Defaults to CanvasScaleMode.CanvasItem.
Example
import { Rapid, Color, TextureFilterMode } from "rapid-render";

const rapid = new Rapid({
  canvas: document.getElementById("game-canvas") as HTMLCanvasElement,
  logicWidth: 1280,
  logicHeight: 720,
  backgroundColor: new Color(30, 30, 30, 255),
  antialias: false,
  textureFilter: TextureFilterMode.NEAREST,
});

Public Properties

PropertyTypeDescription
glWebGL2RenderingContextThe active WebGL2 context. Use for low-level GL calls.
canvasHTMLCanvasElementThe target canvas element passed at construction.
textureTextureManagerManager for creating and caching textures.
matrixStackMatrixStackHierarchical transform stack. See MatrixStack.
matrixMatrixStoreDirect access to the flat matrix buffer. See MatrixStore.
logicWidthnumberLogical coordinate-space width (CSS pixels).
logicHeightnumberLogical coordinate-space height (CSS pixels).
physicsWidthnumberGPU backbuffer width in physical pixels.
physicsHeightnumberGPU backbuffer height in physical pixels.
dprnumberDevice pixel ratio (window.devicePixelRatio).
backgroundColorColorClear color used by clear(). Writable at any time.
drawcallCountnumberNumber of WebGL draw calls issued since the last clear(). Useful for performance profiling.
widthnumberGetter — alias for logicWidth.
heightnumberGetter — 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 call flush() explicitly.

clear()

clear(): void
Clears the active framebuffer using backgroundColor, resets drawcallCount to zero, and calls matrixStack.reset() to wipe all saved transform state. Call this at the start of every frame.
function gameLoop() {
  rapid.clear();

  rapid.drawSprite({ texture: backgroundTexture });
  rapid.drawSprite({ texture: playerTexture, x: playerX, y: playerY });

  requestAnimationFrame(gameLoop);
}

flush()

flush(): void
Immediately submits any pending batched draw calls to the GPU and releases the active rendering region. Rapid calls 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.
rapid.drawSprite({ texture: myTexture });
rapid.flush(); // ensure the sprite is drawn before raw GL work
gl.readPixels(...);

resize(logicWidth, logicHeight, cssWidth?, cssHeight?)

resize(logicWidth: number, logicHeight: number, cssWidth?: number, cssHeight?: number): void
Updates the viewport and orthographic projection. Flush is called internally. If cssWidth/cssHeight are provided, the canvas style.width and style.height are updated as well.
logicWidth
number
required
New logical width. Draw-call coordinates use this space.
logicHeight
number
required
New logical height.
cssWidth
number
Optional CSS display width. Updates canvas.style.width and recalculates physicsWidth = cssWidth × dpr.
cssHeight
number
Optional CSS display height.
window.addEventListener("resize", () => {
  rapid.resize(1280, 720, window.innerWidth, window.innerHeight);
});

Settings Methods

setTextureFilter(filter)

setTextureFilter(filter: TextureFilterMode): void
Updates the default texture sampling filter used when new textures are uploaded. Takes effect for textures loaded after this call.
filter
TextureFilterMode
required
TextureFilterMode.NEAREST for hard-edged pixel art; TextureFilterMode.LINEAR for smooth bilinear filtering.
rapid.setTextureFilter(TextureFilterMode.LINEAR);

setAntialias(antialias)

setAntialias(antialias: boolean): void
Sets the 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.
antialias
boolean
required
true to enable antialiasing; false to disable.

Draw Methods

All draw methods accept an options object that extends ITransformOptions, 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)

drawSprite(options: ISpriteOptions): void
Draws a textured quad using the fast sprite batching path.
options.texture
Texture
required
The texture (or atlas sub-region) to render.
options.color
Color
Tint color multiplied with every fragment. Default white (0xFFFFFFFF).
options.flipX
boolean
Mirror the sprite horizontally.
options.flipY
boolean
Mirror the sprite vertically.
options.padding
number
Expands the rendered quad by this many pixels on every side, allowing shader effects (e.g. outlines) to bleed outside the original sprite boundary.
options.shader
DrawShader
Custom GLShader or CustomGlShader to override the default sprite shader.
rapid.drawSprite({
  texture: heroTexture,
  x: 100,
  y: 200,
  rotation: Math.PI / 6,
  origin: 0.5,          // pivot at centre
  flipX: false,
  color: new Color(255, 200, 200, 255),
});

drawRect(options)

drawRect(options: IRectOptions): void
Draws a filled rectangle, optionally textured.
options.width
number
required
Rectangle width in logical pixels.
options.height
number
required
Rectangle height in logical pixels.
options.color
Color
Fill color. Defaults to opaque white.
options.texture
Texture
Optional texture stretched over the rectangle.
rapid.drawRect({
  width: 200,
  height: 100,
  x: 50,
  y: 50,
  color: new Color(80, 160, 255, 200),
});

drawCircle(options)

drawCircle(options: ICircleOptions): void
Draws a filled circle approximated by a triangle fan.
options.radius
number
required
Circle radius in logical pixels.
options.color
Color
Fill color. Defaults to opaque white.
options.segments
number
Number of triangles used to approximate the circle. Higher values produce smoother edges at a cost of more vertices. Default 32.
rapid.drawCircle({
  radius: 64,
  x: 400,
  y: 300,
  color: new Color(255, 100, 100, 255),
  segments: 48,
});

drawLine(options)

drawLine(options: ILineOptions): void
Draws a polyline with configurable width, caps, and optional texture.
options.points
Vec2[]
required
Array of control points defining the line path. Minimum 2 points required.
options.width
number
Stroke width in logical pixels. Default 1.
options.color
Color
Stroke color.
options.closed
boolean
When true, connects the last point back to the first.
options.roundCap
boolean
Adds semicircular caps at both ends of an open polyline.
options.texture
Texture
Texture to map along the line.
options.textureMode
LineTextureMode
STRETCH maps the texture once across the full length; REPEAT tiles it.
rapid.drawLine({
  points: [new Vec2(0, 0), new Vec2(200, 100), new Vec2(400, 0)],
  width: 4,
  color: new Color(255, 255, 0, 255),
  roundCap: true,
});

drawGraphic(options)

drawGraphic(options: IGraphicOptions): void
Draws arbitrary geometry from a list of points.
options.points
DrawPoint[]
required
Vertices as Vec2 or {x, y} objects.
options.color
Color | Color[]
Uniform tint or per-vertex color array.
options.drawMode
number
WebGL drawing mode constant (e.g. gl.TRIANGLES, gl.TRIANGLE_FAN). Defaults to gl.TRIANGLES.
options.uv
DrawPoint[]
Per-vertex UV coordinates mapped to options.texture.
options.texture
Texture
Optional texture to sample in the graphic shader.
rapid.drawGraphic({
  drawMode: rapid.gl.TRIANGLES,
  points: [
    { x: 0,   y: -50 },
    { x: 50,  y: 50  },
    { x: -50, y: 50  },
  ],
  color: new Color(255, 200, 0, 255),
  x: 300,
  y: 300,
});

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?)

startGraphic(
  drawMode?: number,
  texture?: Texture,
  shader?: GLShader | CustomGlShader,
  customMatrix?: number
): void
Begins a new geometry batch in the graphic region. The current world matrix is used unless customMatrix provides a different matrix index from MatrixStore.
drawMode
number
WebGL primitive type. Default gl.TRIANGLES.
texture
Texture
Texture bound during this batch.
shader
GLShader | CustomGlShader
Override shader for this batch.
customMatrix
number
Index into MatrixStore to use as the transform. Defaults to matrixStack.curWorldM.

startMaskGraphic(drawMode?, texture?, customMatrix?)

startMaskGraphic(
  drawMode?: number,
  texture?: Texture,
  customMatrix?: number
): void
Starts a geometry batch that uses the internal mask shader, rendering geometry into the stencil buffer rather than the colour buffer. Use this before addGraphicVertex / addRectVertex / addCircleVertex / endGraphic() when you want to build mask shapes from raw vertices instead of using startDrawMask.
drawMode
number
WebGL primitive type. Default gl.TRIANGLES.
texture
Texture
Optional texture whose alpha channel may be used to shape the mask.
customMatrix
number
Index into MatrixStore to use as the transform. Defaults to matrixStack.curWorldM.
rapid.startDrawMask();
rapid.startMaskGraphic(rapid.gl.TRIANGLE_FAN);
rapid.addGraphicVertex(0,   0);
rapid.addGraphicVertex(100, 0);
rapid.addGraphicVertex(100, 100);
rapid.addGraphicVertex(0,   100);
rapid.endGraphic();
rapid.endDrawMask();

addGraphicVertex(x, y, u?, v?, color?)

addGraphicVertex(
  x: number,
  y: number,
  u?: number,
  v?: number,
  color?: number
): void
Pushes a single vertex into the current graphic batch.
x
number
required
X coordinate in local space.
y
number
required
Y coordinate in local space.
u
number
U texture coordinate (0–1). Default 0.
v
number
V texture coordinate (0–1). Default 0.
color
number
32-bit ABGR vertex color. Default 0xFFFFFFFF (opaque white).

addRectVertex(w, h, color?)

addRectVertex(w: number, h: number, color?: Color): void
Pushes four vertices for a rectangle from (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?)

addCircleVertex(r: number, color?: Color, segments?: number): void
Pushes 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()

endGraphic(): void
Closes the current geometry batch, making it eligible for the next flush. Full example — custom hexagon
rapid.startGraphic(rapid.gl.TRIANGLE_FAN);
rapid.addGraphicVertex(0, 0, 0.5, 0.5); // centre vertex

const sides = 6;
for (let i = 0; i <= sides; i++) {
  const angle = (i / sides) * Math.PI * 2;
  rapid.addGraphicVertex(
    Math.cos(angle) * 40,
    Math.sin(angle) * 40,
    0.5 + Math.cos(angle) * 0.5,
    0.5 + Math.sin(angle) * 0.5,
  );
}
rapid.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)

enterRenderTexture(rt: RenderTexture): void
Binds 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()

leaveRenderTexture(): void
Unbinds the current render texture, restores the main canvas as the render target, and resets the viewport and projection to the logical canvas dimensions.

drawToRenderTexture(rt, cb, color?)

drawToRenderTexture(
  rt: RenderTexture,
  cb: () => void,
  color?: Color | null
): void
Convenience wrapper that enters the render texture, optionally clears it, executes cb, and then leaves the render texture — even if cb throws.
rt
RenderTexture
required
The target render texture.
cb
() => void
required
Draw calls to execute inside the render texture.
color
Color | null
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).
const offscreen = rapid.texture.createRenderTexture({ width: 512, height: 512 });

rapid.drawToRenderTexture(offscreen, () => {
  rapid.drawSprite({ texture: backgroundTex });
  rapid.drawSprite({ texture: characterTex, x: 200, y: 150 });
});

// Later in the main frame:
rapid.drawSprite({ texture: offscreen, x: 0, y: 0 });

clearRenderTexture(color?)

clearRenderTexture(color?: Color): void
Clears the currently-bound render texture to color. Defaults to transparent black. Must be called while a render texture is active (i.e. inside an enterRenderTexture / leaveRenderTexture block).

applyFilters(source, shaders)

applyFilters(source: Texture, shaders: CustomGlShader[]): RenderTexture
Applies a chain of custom shaders to 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.
source
Texture
required
The input texture to start the filter chain from.
shaders
CustomGlShader[]
required
Ordered array of shaders to apply. Must not be empty.
return
RenderTexture
The render texture containing the final filtered result. Render it with drawSprite to display on screen.
const result = rapid.applyFilters(mySprite, [blurShader, outlineShader]);

rapid.drawSprite({ texture: result });
applyFilters saves and restores the matrix stack internally, so it is safe to call mid-frame without disrupting your transform hierarchy.

Convenience Wrappers

These methods bundle a common setup / teardown pattern into a single call, using try / finally to guarantee cleanup even if the callback throws.

withTransform(cb, transform?, width?, height?)

withTransform(
  cb: () => void,
  transform?: ITransformOptions,
  width?: number,
  height?: number
): void
Saves the current matrix state, optionally applies a transform, executes cb, then restores. When transform is omitted a bare save/restore wraps the callback. When transform.saveTransform is false the save step is skipped.
cb
() => void
required
Draw calls to execute within the transform.
transform
ITransformOptions
Transform options (position, rotation, scale, origin, …).
width
number
Logical width passed to origin anchor resolution. Default 0.
height
number
Logical height passed to origin anchor resolution. Default 0.
// Simple save/restore
rapid.withTransform(() => {
  rapid.matrixStack.translate(100, 100);
  rapid.drawSprite({ texture: tileTexture });
});

// With a full transform applied
rapid.withTransform(() => {
  rapid.drawSprite({ texture: heroTexture });
}, { x: 320, y: 240, rotation: Math.PI / 4, origin: 0.5 },
   heroTexture.width, heroTexture.height);

withBlendMode(mode, cb)

withBlendMode(mode: BlendMode, cb: () => void): void
Sets the blend mode to mode, runs cb, then restores BlendMode.NORMAL.
rapid.withBlendMode(BlendMode.ADD, () => {
  rapid.drawSprite({ texture: glowTexture });
  rapid.drawSprite({ texture: sparkTexture });
});

withMask(maskCb, drawCb, type?, ref?)

withMask(
  maskCb: () => void,
  drawCb: () => void,
  type?: MaskType,
  ref?: number
): void
High-level stencil mask helper. Clears the stencil buffer, writes the mask geometry from maskCb into the stencil buffer (invisible to the colour buffer), then draws drawCb clipped to the stencil region.
maskCb
() => void
required
Geometry that defines the mask shape.
drawCb
() => void
required
Draw calls rendered within the mask.
type
MaskType
MaskType.EQUAL renders inside the mask (default); MaskType.NOT_EQUAL renders outside it.
ref
number
Stencil reference value. Default 1.
rapid.withMask(
  () => rapid.drawRect({ width: 200, height: 200, x: 100, y: 100 }),
  () => rapid.drawSprite({ texture: sceneTexture }),
);

withScissor(x, y, w, h, cb)

withScissor(x: number, y: number, width: number, height: number, cb: () => void): void
Enables GPU scissor clipping to the specified rectangle (in logical coordinates), runs cb, then disables scissoring.
rapid.withScissor(50, 50, 300, 200, () => {
  rapid.drawSprite({ texture: mapTexture });
});

Mask / Stencil Methods

For finer-grained control over multi-layer stencil masks, use the low-level methods directly.

startDrawMask(ref?, mask?)

startDrawMask(ref?: number, mask?: number): void
Begins writing to the stencil buffer. Colour buffer writes are disabled during this phase. All geometry drawn after this call writes ref into the stencil.
ref
number
Stencil write value. Default 1.
mask
number
Stencil bitmask. Default 0xFF.

endDrawMask()

endDrawMask(): void
Ends the stencil-write phase and re-enables colour buffer writing.

clearMask(mask?)

clearMask(mask?: number): void
Clears the specified stencil bits. Default mask 0xFF clears all stencil layers.

enterMask(type, ref?, mask?)

enterMask(type: MaskType, ref?: number, mask?: number): void
Activates stencil testing so that subsequent draw calls are clipped according to the mask written by startDrawMask.
type
MaskType
required
EQUAL draws inside; NOT_EQUAL draws outside.
ref
number
Reference value to test against. Default 1.
mask
number
Bitmask. Default 0xFF.

exitMask()

exitMask(): void
Disables stencil testing and restores the default stencil state (ALWAYS pass).

drawMaskImage(options)

drawMaskImage(options: IMaskImageOptions): void
Convenience helper that renders options.texture into the stencil buffer as a mask rectangle using the texture’s alpha channel.
options.texture
Texture
required
Texture whose alpha drives the mask shape.

Blend Mode Methods

setBlendMode(mode)

setBlendMode(mode: BlendMode): void
Flushes pending geometry, then configures WebGL’s blendFuncSeparate for the requested mode. The alpha channel is handled separately from RGB to avoid darkening artifacts on off-screen render textures.
rapid.setBlendMode(BlendMode.MULTIPLY);
rapid.drawSprite({ texture: shadowTexture });
rapid.setBlendMode(BlendMode.NORMAL);
Prefer withBlendMode() when a blend mode only applies to a subset of draw calls — it guarantees restoration to NORMAL even if an exception is thrown.

Scissor Methods

startScissor(x, y, width, height)

startScissor(x: number, y: number, width: number, height: number): void
Enables the WebGL scissor test restricted to the given rectangle expressed in logical coordinates. Internally converts to physical pixels and flips the Y axis for WebGL’s bottom-left origin.

endScissor()

endScissor(): void
Disables the scissor test and restores full-canvas rendering.

Region Method

enterRegion(region, customShader?)

enterRegion(region: Region, customShader?: GLShader | CustomGlShader): void
Switches the renderer to the specified 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.
region
Region
required
The rendering region to activate (e.g. rapid.spriteRegion, rapid.graphicRegion).
customShader
GLShader | CustomGlShader
Optional shader override for the activated region.

Camera / Coordinate Utilities

renderCamera(transform)

renderCamera(transform: ITransformOptions): void
Applies 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.
rapid.renderCamera({ x: cameraX, y: cameraY, rotation: cameraAngle });

logicToPhysics(p)

logicToPhysics(p: Vec2): Vec2
Converts a point from logical coordinate space to physical (GPU pixel) space.

physicsToLogic(p)

physicsToLogic(p: Vec2): Vec2
Converts a point from physical pixel space back to logical coordinate space.

cssToDevicePixel(p)

cssToDevicePixel(p: Vec2): Vec2
Multiplies the point by the device pixel ratio, converting CSS pixel coordinates to hardware pixel coordinates.

devicePixelToCss(p)

devicePixelToCss(p: Vec2): Vec2
Divides the point by the device pixel ratio, converting hardware pixel coordinates to CSS pixel coordinates.

Enums

BlendMode

Controls how incoming (source) fragments are composited with the existing (destination) colour.
ValueDescription
BlendMode.NORMALStandard alpha blending. Suitable for most sprites and UI.
BlendMode.ADDAdditive blending — RGB values are summed. Ideal for glows, fire, and energy effects.
BlendMode.MULTIPLYMultiplies source and destination colours. Creates shadows and darkening effects.
BlendMode.SCREENInverts, multiplies, then inverts again. Softer additive look, avoids harsh white burn-out.
BlendMode.ERASESubtracts source alpha from the destination. Useful for punch-through transparency in render textures.

MaskType

Determines which pixels survive the stencil test.
ValueDescription
MaskType.EQUALOnly pixels where stencil equals the reference value are drawn (render inside the mask).
MaskType.NOT_EQUALOnly pixels where stencil does not equal the reference value are drawn (render outside the mask).

TextureFilterMode

Default sampling filter applied to textures uploaded through TextureManager.
ValueDescription
TextureFilterMode.NEARESTNearest-neighbour filtering. Preserves hard pixel edges; recommended for pixel art.
TextureFilterMode.LINEARBilinear filtering. Smooths magnified textures; better for high-resolution artwork.

CanvasScaleMode

Determines how the WebGL backbuffer relates to the CSS display size.
ValueDescription
CanvasScaleMode.CanvasItemThe backbuffer matches the physical screen resolution (logicSize × dpr). Rotated sprites and lines are rasterised at full display resolution for maximum sharpness.
CanvasScaleMode.ViewportThe 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.

Build docs developers (and LLMs) love