Skip to content

SpriteBatch

Collects sprite draw calls between begin / end and flushes them as instanced GPU draws grouped by texture. You can call begin/end multiple times per frame.

import { SpriteBatch } from 'webgpu-spritebatch'
const batch = new SpriteBatch(surface, { maxSprites: 10_000 })
ParameterTypeDescription
surfaceRenderSurfaceThe render surface to draw to
options.maxSpritesnumberMaximum sprites per begin/end pair (default 10_000)

Start a batch. All configuration is set here.

batch.begin({
sortMode: 'frontToBack',
blendState: BlendState.alphaBlend,
samplerState: SamplerState.pointClamp,
effect: SpriteEffect.alphaCutout,
transformMatrix: cam.getTransformMatrix(),
target: renderTexture,
time: elapsed,
})
FieldTypeDefaultDescription
sortModeSpriteSortMode'deferred'How sprites are ordered before rendering
blendStateBlendStateDescriptorBlendState.alphaBlendGPU blend mode
samplerStateSamplerStateDescriptorSamplerState.linearClampTexture filtering/wrapping
effectSpriteEffectDescriptorSpriteEffect.defaultTexturedShader effect
effectParamsRecord<string, number | number[]>Custom shader parameter values
transformMatrixFloat32Arrayidentity4x4 column-major transform
timenumber0Elapsed time (accessible in shaders as screen.size.z)
targetRenderDestinationsurfaceRender destination

Queue one sprite.

batch.draw(tex, {
position: [100, 80],
scale: 2,
rotation: 0.1,
origin: [tex.width / 2, tex.height / 2],
color: Color.white,
layerDepth: 0.5,
})
FieldTypeDefaultDescription
position[x, y][0, 0]Top-left position in CSS pixels
destinationRectRectDraw into an explicit rectangle (overrides position/scale)
sourceRectRectfull textureSub-region of the texture
colorColorRGBAwhiteTint color multiplied with the texture
rotationnumber0Rotation in radians
origin[x, y][0, 0]Rotation/position pivot in source-texture pixels
scalenumber | [x, y]1Scale factor
flipSpriteFlip'none''horizontal', 'vertical', or 'both'
layerDepthnumber0Depth value (0–1) for sorting and depth testing

Sort, upload, and render all queued sprites.

batch.end()
ModeBehavior
'deferred'Draw order preserved (no sort)
'texture'Grouped by texture ID
'frontToBack'Ascending layerDepth
'backToFront'Descending layerDepth