LittleJS 1.30.1

Draw

LittleJS Drawing System

  • Hybrid rendering with both Canvas2D and WebGL support
  • Optimized tile sheet sprite rendering using WebGL batching
  • Primitive drawing for polygons, ellipses, and lines
  • Tile-based rendering with TileInfo and TextureInfo classes
  • Text rendering with custom fonts and ImageFont support
  • Color and additive color blending for effects
  • Rotation, mirroring, and scaling transformations
  • Camera system with position, scale, and rotation
  • Multiple canvas support (main, WebGL, work canvases)
  • Gradient fills and outlined shapes
  • Image manipulation and color tinting

Rendering Architecture:

  • glCanvas: WebGL canvas for accelerated sprite batch rendering
  • mainCanvas: Canvas2D overlay for text, UI, and custom drawing
  • All draw functions default to WebGL when enabled, can force Canvas2D with useWebGL parameter

Classes

Functions

Members

Typedefs

Functions

cameraFit(center, size, worldMargin, screenInset) → numberengineDraw.js:1865

Fit the camera to a rectangle in world space by setting cameraPos and cameraScale

  • worldMargin pads the content rectangle in world units, so the gap scales with the content on resize
  • screenInset reserves space in screen pixels on each viewport edge (for example a HUD band) and re-centers the content away from that edge, so the reserved band stays a fixed pixel size on resize
  • worldMargin and screenInset may each be a number for all sides, a Vector2 (x=left/right, y=top/bottom), or an object with any of {top, right, bottom, left}
center Vector2

Center of the rectangle in world space

size Vector2

Size of the rectangle in world space

worldMargin number|Vector2|CameraFitSides optional

World space padding added around the content rectangle

screenInset number|Vector2|CameraFitSides optional

Screen space padding in pixels reserved on each viewport edge

Returns
  • The new camera scale
cameraShake(amount, direction)engineDraw.js:1940

Shake the camera, for a hit or an explosion: adds to the shake, which fades on its own by cameraShakeDecay

  • The view moves by smooth noise scaled by the shake squared, so a small one is gentle and a big one is wild, up to cameraShakeDistance and cameraShakeAngle
  • It moves only what is drawn, in 2D and in 3D: cameraPos and cameraAngle are the game's own between frames; move the camera in an update, not while a frame draws, where cameraPos is the shaken one: a new cameraPos set there is kept, shake and all, and one changed in place is put back after the frame
  • It holds while the game is paused or at a time scale of 0
  • A direction puts the shake more on one axis, vec2(0, 1) for a heavy landing; each axis fades on its own, so a shake on one does not change the other's, and the turn adds the most each shake puts on one axis, so it is never less than either
amount number optional, default 0.5

How much to add, the shake is at most 1

direction Vector2 optional

How much of it goes to each axis, 0 to 1

cameraShake(.6, vec2(.2, 1)); // a heavy landing, mostly up and down
combineCanvases()engineDraw.js:2060

Combines LittleJS canvases onto the main canvas This is necessary for things like screenshots and video

drawCanvas2D(pos, size, angle, mirror, drawFunction, screenSpace, context)engineDraw.js:1419

Draw directly to a 2d canvas context in world space. The Y axis is flipped so world-Y-up coordinates render right-side up (matches the WebGL path). Callers whose drawing depends on Y direction (e.g. linear gradients) should flip their own Y endpoints accordingly.

pos Vector2
size Vector2
angle number optional, default 0
mirror boolean optional, default false
drawFunction Canvas2DDrawFunction optional

Needed, marked optional only because the ones before it are

screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional, default drawContext
drawCircle(pos, size, color, lineWidth, lineColor, useWebGL, screenSpace, context)engineDraw.js:1298

Draw colored circle using passed in point

pos Vector2
size number optional, default 1

Diameter

color Color optional, default WHITE
lineWidth number optional, default 0
lineColor Color optional, default BLACK
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawCircleGradient(pos, size, colorInner, colorOuter, useWebGL, screenSpace, context)engineDraw.js:1394

Draw a circle filled with a radial gradient from the center to the rim

  • Best when batched with other untextured polys
  • If drawing mostly textured sprites, bake the gradient into a texture and use drawTile instead
  • Stacking gradients at the exact same position may show a faint vertical artifact
pos Vector2
size number optional, default 1

Diameter

colorInner Color optional, default WHITE
colorOuter Color optional, default CLEAR_WHITE
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawEllipse(pos, size, color, angle, lineWidth, lineColor, useWebGL, screenSpace, context)engineDraw.js:1224

Draw colored ellipse using passed in point

pos Vector2
size Vector2 optional, default vec2(1)

Width and height diameter

color Color optional, default WHITE
angle number optional, default 0
lineWidth number optional, default 0
lineColor Color optional, default BLACK
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawEllipseGradient(pos, size, colorInner, colorOuter, angle, useWebGL, screenSpace, context)engineDraw.js:1318

Draw an ellipse filled with a radial gradient from the center to the rim

  • Best when batched with other untextured polys
  • If drawing mostly textured sprites, bake the gradient into a texture and use drawTile instead
  • Stacking gradients at the exact same position may show a faint vertical artifact
pos Vector2
size Vector2 optional, default vec2(1)

Width and height diameter

colorInner Color optional, default WHITE
colorOuter Color optional, default CLEAR_WHITE
angle number optional, default 0
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawLine(posA, posB, width, color, pos, angle, useWebGL, screenSpace, context)engineDraw.js:1104

Draw colored line between two points

posA Vector2
posB Vector2
width number optional, default 0.1
color Color optional, default WHITE
pos Vector2 optional, default vec2()

Offset to apply

angle number optional, default 0

Angle to rotate by

useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawLineList(points, width, color, wrap, pos, angle, useWebGL, screenSpace, context)engineDraw.js:1045

Draw connected lines between a series of points

points Array<Vector2>

In its own space, y up, in screen space too, where drawLine's ends go down

width number optional, default 0.1
color Color optional, default WHITE
wrap boolean optional, default false

Should the last point connect to the first?

pos Vector2 optional, default vec2()

Offset to apply

angle number optional, default 0

Angle to rotate by

useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawPoly(points, color, lineWidth, lineColor, pos, angle, useWebGL, screenSpace, context)engineDraw.js:1162

Draw colored polygon using passed in points

  • WebGL fills a polygon whose edges do not cross, concave or not; a self crossing one, like a star through its outer points, fills wrong there, so draw it as its simple outline or in parts
points Array<Vector2>

In its own space, y up, in screen space too, where drawLine's ends go down

color Color optional, default WHITE
lineWidth number optional, default 0
lineColor Color optional, default BLACK
pos Vector2 optional, default vec2()

Offset to apply

angle number optional, default 0

Angle to rotate by

useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawRect(pos, size, color, angle, useWebGL, screenSpace, context)engineDraw.js:849

Draw colored rect centered on pos

pos Vector2
size Vector2 optional, default vec2(1)
color Color optional, default WHITE
angle number optional
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawRectGradient(pos, size, colorTop, colorBottom, angle, useWebGL, screenSpace, context)engineDraw.js:864

Draw a rect centered on pos with a gradient from top to bottom

pos Vector2
size Vector2 optional, default vec2(1)
colorTop Color optional, default WHITE
colorBottom Color optional, default CLEAR_WHITE
angle number optional, default 0
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawRegularPoly(pos, size, sides, color, lineWidth, lineColor, angle, useWebGL, screenSpace, context)engineDraw.js:1128

Draw colored regular polygon using passed in number of sides

pos Vector2
size Vector2 optional, default vec2(1)
sides number optional, default 3
color Color optional, default WHITE
lineWidth number optional, default 0
lineColor Color optional, default BLACK
angle number optional, default 0
useWebGL boolean optional, default glEnable
screenSpace boolean optional, default drawScreenSpace
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional
drawText(text, pos, size, color, lineWidth, lineColor, textAlign, font, fontStyle, maxWidth, angle, context)engineDraw.js:1463

Draw text on main canvas in world space Automatically splits new lines into rows

text string|number
pos Vector2
size number optional, default 1
color Color optional, default WHITE
lineWidth number optional, default 0
lineColor Color optional, default BLACK
textAlign 'left'|'center'|'right' optional, default center
font string optional, default fontDefault
fontStyle string optional
maxWidth number optional
angle number optional, default 0
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional, default drawContext
drawTextScreen(text, pos, size, color, lineWidth, lineColor, textAlign, font, fontStyle, maxWidth, angle, context)engineDraw.js:1564

Draw text in screen space Automatically splits new lines into rows

  • An icon registered with setTextIcon is drawn where its name is written between colons, ':coin:'
text string|number
pos Vector2
size number
color Color optional, default WHITE
lineWidth number optional, default 0
lineColor Color optional, default BLACK
textAlign 'left'|'center'|'right' optional, default center
font string optional, default fontDefault
fontStyle string optional
maxWidth number optional
angle number optional, default 0

Clockwise, like the other screen space draws

context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional, default drawContext
drawTextureWrapped(pos, size, wrapCount, texture, color, angle, additiveColor, useWebGL, screenSpace, context)engineDraw.js:931

Draw a texture tiled (wrapped) across a rectangle in world space. Useful for backgrounds, repeating patterns, and seamless fills. The whole texture is tiled — sub-region (TileInfo) wrapping is not supported.

pos Vector2

Center of the rect in world space

size Vector2

Size of the rect in world space

wrapCount Vector2

How many times the texture repeats (x, y)

texture TextureInfo|number optional, default 0

TextureInfo or texture index into textureInfos

color Color optional, default WHITE

Color to modulate with

angle number optional, default 0

Angle to rotate by

additiveColor Color optional

Additive color to be applied if any

useWebGL boolean optional, default glEnable

Use accelerated WebGL rendering?

screenSpace boolean optional, default drawScreenSpace

Are pos and size in screen space?

context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional

Canvas 2D context to draw to

drawTile(pos, size, tileInfo, color, angle, mirror, additiveColor, useWebGL, screenSpace, context)engineDraw.js:752

Draw textured tile centered in world space

pos Vector2

Center of the tile in world space

size Vector2 optional, default vec2(1)

Size of the tile in world space

tileInfo TileInfo optional

Tile info to use, untextured if undefined

color Color optional, default WHITE

Color to modulate with

angle number optional, default 0

Angle to rotate by

mirror boolean optional

Is the image flipped left to right?

additiveColor Color optional

Additive color to be applied if any

useWebGL boolean optional, default glEnable

Use accelerated WebGL rendering?

screenSpace boolean optional, default drawScreenSpace

Are the pos and size in screen space?

context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D optional

Canvas 2D context to draw to

getCameraSize() → Vector2engineDraw.js:1843

Get the size of the camera window in world space

isFullscreen() → booleanengineDraw.js:2184

Returns true if fullscreen mode is active

isOnScreen(pos, size) → booleanengineDraw.js:2000

Check if a box, point, or circle is on screen with a circle test If size is a Vector2, uses the length as diameter This can be used to cull offscreen objects from render or update

pos Vector2

world space position

size Vector2|number optional, default 0

world space size or diameter

loadTexture(textureIndex, src) → Promise<TextureInfo>asyncengineDraw.js:1709

Load a texture at a specific index after engineInit, the images passed to engineInit load this way

textureIndex number

Index to store the texture at, an unused one

src string optional

Image source path

Returns

Resolves to the texture info once the image loads, or fails to with a warning

screenToWorld(screenPos) → Vector2engineDraw.js:1741

Convert from screen to world space coordinates

screenPos Vector2
screenToWorldDelta(screenDelta) → Vector2engineDraw.js:1785

Convert from screen to world space coordinates for a directional vector (no translation)

screenDelta Vector2
screenToWorldTransform(screenPos, screenSize, screenAngle) → [Vector2, Vector2, number]engineDraw.js:1827

Convert screen space transform to world space

screenPos Vector2
screenSize Vector2
screenAngle number optional, default 0
setAdditiveBlendMode(additive)engineDraw.js:2033

Enable additive blending

additive boolean optional, default true
setBackgroundCanvas(canvas)engineDraw.js:2055

Set an extra canvas to composite behind the engine canvases when combining Plugins that insert their own canvas below the LittleJS canvases should set this so it appears in screenshots

canvas HTMLCanvasElement optional
setCursor(cursorStyle)engineDraw.js:2203

Set the cursor style

cursorStyle string optional, default auto

CSS cursor style (auto, none, crosshair, etc)

setShader(shader)engineDraw.js:2044

Set the Shader that 2D draws use from now on, none for the engine's own

  • The object render loop sets each object's own shader, so this is for draws in gameRender and gameRenderPost
shader Shader optional
setTextIcon(name, tileInfo)engineDraw.js:1633

Register a tile to show in text: written between colons in any text drawTextScreen draws, drawText and the UI system's text included, it is drawn in its place, as tall as the text, 'Gold: :coin: 25'

  • Only a registered name is replaced, so other text with colons, like a time of 5:30, stays as it is
  • ImageFont text shows them too, each as tall as a character
name string

Letters, digits, _ and -

tileInfo TileInfo optional

Left out to take the name off

setTextIcon('coin', tile(5));
drawTextScreen('Gold: :coin: 25', vec2(100, 50), 40);
tile(index, size, texture, padding, bleed) → TileInfoengineDraw.js:120

Create a tile info object using a grid based system

  • This can take vecs or floats for easier use and conversion
  • If an index is passed in, the tile size and index will determine the position
index Vector2|number optional, default 0

Index of the tile in 1d or 2d form

size Vector2|number optional

Size of tile in pixels

texture TextureInfo|number optional, default 0

Texture index or info to use

padding number optional

How many pixels padding around tiles

bleed number optional

How many pixels smaller to draw tiles

tile(2)                       // a tile at index 2 using the default tile size of 16
tile(5, 8)                    // a tile at index 5 using a tile size of 8
tile(1, 16, 3)                // a tile at index 1 of size 16 on texture 3
tile(vec2(4,8), vec2(30,10))  // a tile at index (4,8) with a size of (30,10)
toggleFullscreen()engineDraw.js:2188

Toggle fullscreen mode

worldToScreen(worldPos) → Vector2engineDraw.js:1761

Convert from world to screen space coordinates

worldPos Vector2
worldToScreenDelta(worldDelta) → Vector2engineDraw.js:1805

Convert from world to screen space coordinates for a directional vector (no translation)

worldDelta Vector2

Members

backgroundCanvas : HTMLCanvasElementengineDraw.js:67

Extra canvas to composite behind the engine canvases when combining canvases Set by plugins that render to their own canvas below the LittleJS canvases

drawContext : CanvasRenderingContext2D|OffscreenCanvasRenderingContext2DengineDraw.js:41

The default 2d context to use for drawing, usually mainContext

drawCount : numberengineDraw.js:84

Keeps track of how many draw calls there were each frame for debugging

engineImageFont : ImageFontengineDraw.js:2214

Engine font image, 8x8 font provided by the engine

mainCanvas : HTMLCanvasElementengineDraw.js:28

The primary 2D canvas visible to the user

mainCanvasSize : Vector2engineDraw.js:74

The size of the main canvas (and other secondary canvases) in css pixels

  • This is the screen space coordinate system, matching mousePos
  • With canvasPixelRatio set the backing store is larger than this
mainContext : CanvasRenderingContext2DengineDraw.js:36

2d context for mainCanvas

  • Scaled by canvasPixelRatio, so drawing to it is in css pixels
  • getImageData and putImageData ignore that scale and work in backing store pixels, so use workReadCanvas to read pixels back instead of this
primitiveCount : numberengineDraw.js:90

Keeps track of how many primitives were drawn each frame for debugging A single draw call can render many primitives (e.g. a WebGL sprite batch).

textureInfos : Array<TextureInfo>engineDraw.js:79

Array containing texture info for batch rendering system

workCanvas : OffscreenCanvasengineDraw.js:46

Offscreen canvas that can be used for image processing

workContext : OffscreenCanvasRenderingContext2DengineDraw.js:51

Offscreen canvas that can be used for image processing

workReadCanvas : OffscreenCanvasengineDraw.js:56

Offscreen canvas with willReadFrequently that can be used for image processing

workReadContext : OffscreenCanvasRenderingContext2DengineDraw.js:61

Offscreen canvas with willReadFrequently that can be used for image processing

Typedefs

CameraFitSides : ObjectengineDraw.js:1845

Padding for each side of a rectangle, the sides left out are 0

top number optional
right number optional
bottom number optional
left number optional
Canvas2DDrawFunction(context) → voidengineDraw.js:1400
context CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D
ShaderUniform : number|boolean|Vector2|Color|ArrayLike<number>|Object|ObjectengineDraw.js:598

A value a Shader's snippet reads as a uniform: a number, a boolean, a Vector2, a Vector3, a Color, a Matrix4, or a list of 2, 3, 4, 9 or 16 numbers

SpriteAnimationEndCallback() → voidengineDraw.js:399