LITECANVAS

Lightweight HTML5 canvas engine suitable for small games and animations for people who enjoy coding: there is no fancy interface, no visual helpers, no gui tools... just coding.

NPM: npm i @litecanvas/litecanvas
CND: https://unpkg.com/@litecanvas/litecanvas/dist/dist.js

const settings = {
  loop: { init, update, draw, resized }
}

litecanvas(settings)

function init() {
  // run once before the game starts
}

function update(dt) {
  // called at 60 fps by default
  // note: `dt` is a fixed deltatime
}

function draw() {
  // use to draw your game graphics
}

function resized() {
  // called when the browser was resized
  // always called once before init()
}

Default Colors

Default Color Palette

8-color palette inspired by https://lospec.com/palette-list/matriax8c

Game Configuration

// Initialize the game
litecanvas(settings = {});

// the game loop callbacks
// if loop = undefined, will use these functions:
// window.init(), window.update(dt), window.draw(), window.resized()
settings.loop = {
  init: function,
  update: function,
  draw: function,
  resized: function
}

// the canvas (by default a new canvas is created)
settings.canvas = null

// make the game screen fill the entire screen
settings.fullscreen = true

// the game screen size
settings.width = settings.height = undefined

// scale the canvas
settings.autoscale = true

// target FPS
settings.fps = 60

// the canvas background color
// accept: null or integer (a color from 0 to 7)
settings.background = null

// enable smooth drawing
settings.antialias = true

// disables antialias and force integer scales
settings.pixelart = false

// set to `false` to disable the default tap events (see TAPPED and TAPPING globals)
// useful to create your own input handler
settings.tapEvents = true

// amount of time (milliseconds) to pause the tapping detection
settings.tappingInterval = 100;

// export all functions to global context
settings.global = true

Functions for Drawing

/**
 * SHAPES DRAWING-RELATED FUNCTIONS
 */

// clear the canvas
// all color argument is a integer (a color from 0 to 7)
// alias: clear
cls(color?: number): void

// draw a color-filled rectangle
rectfill(x, y, w, h, color = 0, radii?: number | number[]): void

// draw a outline rectangle
rect(x, y, w, h, color = 0, radii?: number | number[]): void

// draw a color-filled circle
circfill(x, y, r, color = 0): void

// draw a outline circle
circ(x, y, r, color = 0): void

// draw a line
line(x1, y1, x2, y2, color = 0): void

// Sets the thickness of lines
linewidth(value: number): void

// Sets the line dash pattern used when drawing lines
linedash(value: number | number[], ofsset?: number): void

// Determines the shape used to draw the end points of lines
// Possible values are: "butt", "round" or "square"
linecap(value: string): void

// Determines the shape used to join two line segments where they meet
// Possible values are: "round", "bevel", and "miter"
linejoin(value: string): void

/**
 * TEXT DRAWING-RELATED FUNCTIONS
 */

// draw a text
// alias: print
text(x, y, text, color = 3): void

// set the text alignment and baseline
// default values: align = 'start', baseline = 'top'
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline
textalign(align: string, baseline: string): void

// set the default font family
// default: 'sans-serif'
textfont(fontName: string): void

// set the font size
// default: 32
textsize(size: number): void

// used to draw a text as 'bold' or 'italic'
textstyle(style: string)

// returns the text dimensions like width and height
// when size is omitted, it will use the current font size defined by textsize()
textmetrics(text: string, size?: number)

/**
 * IMAGE DRAWING-RELATED FUNCTIONS
 */

// draw a image
image(x, y, image: Image|HTMLCanvasElement): void

/**
 * IMAGE DRAWING-RELATED FUNCTIONS
 */

// create a offcanvas and to make an image
// see: https://github.com/litecanvas/game-engine/blob/main/samples/paint/paint.js
// see: https://github.com/litecanvas/game-engine/blob/main/samples/pixelart/pixelart.js
paint(width, height, draw: string[]|function, options?: {scale: number}): OffscreenCanvas

/**
 * ADVANCED DRAWING-RELATED FUNCTIONS
 */

// return the current canvas context 2D
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
ctx(): CanvasRenderingContext2D

// save the canvas context
push(): void

// restore the canvas context
pop(): void

// note: before call cliprect or clipcirc you must save the context using push()
// and later, you restore the context using pop()

// Adds a translation transformation to the current matrix
translate(x: number, y: number): void

// Adds a scaling transformation to the canvas units horizontally and/or vertically
scale(x: number, y?: number): void

// Adds a rotation to the transformation matrix
rotate(radians: number): void

// update the transformation matrix
// when `resetFirst = true` uses `context.setTransform()`
// wwhen `resetFirst = false` uses `context.transform()`
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform
transform(a, b, c, d, e, f, resetFirst = true): void

// update the alpha (transparency)
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalAlpha
alpha(value: number): void

// fills the current path
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fill
fill(color: number, path?: Path2D): void

// outlines the current path
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/stroke
stroke(color: number, path?: Path2D): void

// create a Path2D instance
// see: https://developer.mozilla.org/en-US/docs/Web/API/Path2D/Path2D
path(arg?: Path2D | string): Path2D

// update the type of compositing operation
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
blendmode(value: string): void

// Provides filter effects such as blurring and grayscaling.
// It is similar to the CSS filter property and accepts the same values.
// see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
filter(effect: string): void

// create a "circular" clipping region
// see: https://github.com/litecanvas/game-engine/blob/main/samples/clip/clip.js
clipcirc(x, y, width, height): void

// same as above, but create a "rectangular" clipping region
cliprect(x, y, width, height): void

Functions for Sound

// play a predefined sound
// note: `n` must be a sound index (from 0 to 7)
sfx(n = 0, volume = 1, pitch = 0, randomness = 0): AudioBufferSourceNode

// also, you can play a ZzFX array of params
// see: https://killedbyapixel.github.io/ZzFX/
// example: sfx([2,.05,598,.07,0,.19,0,1.32,9.9,-70,0,0,0,0,0,0,.3,.02,0,.04])
sfx(ZzFXparams: Array, volume = 1, pitch = 0, randomness = 0): AudioBufferSourceNode

Math


// Generates a pseudo-random float between min (inclusive) and max (exclusive)
rand(min = 0, max = 1.0): number;

// Generates a pseudo-random integer between min (inclusive) and max (inclusive)
randi(min = 0, max = 1): number;

// Returns `true` or `false` based on random chance (p)
// example: chance(0.25) ? '25% true' : '75% false'
chance(p: number): boolean

// Choose a random item from a Array
choose(arr: Array<T>): T

// Calculates a linear (interpolation) value over `t`.
// example: lerp(0, 50, 0.5) returns 25
// learn more: https://gamedev.net/tutorials/programming/general-and-gameplay-programming/a-brief-introduction-to-lerp-r4954/
lerp(a: number, b: number, t: number): number

// Interpolate between 2 values.
// Optionally, takes a custom periodic function (default = `Math.sin`).
wave(lower, higher, t, fn = Math.sin): number

// Convert degrees to radians
deg2rad(n: number): number

// Convert radians to degrees
rad2deg(n: number): number

// Constrains a number between `min` and `max`.
// example: clamp(50, 0, 100) return 50
// example: clamp(150, 0, 100) return 100
// example: clamp(-10, 0, 100) return 0
clamp(value: number, min: number, max: number): number

// Wraps a number between `min` (inclusive) and `max` (exclusive).
// example: wrap(50,0,100) return 50
// example: wrap(125, 0, 100) return 25
wrap(value, min, max): number

// Re-maps a number from one range to another.
// example: map(2, 0, 10, 0, 100) returns 20
map(val, min1, max1, min2, max2, withinBounds = false ): number

// Maps a number from one range to a value between 0 and 1.
// example: norm(50, 0, 100) returns 0.5
norm(value, min, max): number

// Calculates the positive difference of two given numbers.
// example: diff(20, 30) return 10
// example: diff(-3, 3) return 6
diff(a, b): number

// Returns the sine of a number in radians.
sin(angle: number): number

// Returns the cosine of a number in radians.
cos(angle: number): number

// Returns the tangent of a number in radians.
tan(angle: number): number

// Returns the angle between the positive x-axis
// and the origin (0, 0) to the point (x, y)
atan2(y:number, x: number): number

// Returns the square root of the sum of squares of its arguments
hypot(...ns: number): number

// Returns the absolute value of a number.
abs(n: number): number

// Rounds up and returns the smallest integer greater than or equal to a given number
ceil(n: number): number

// Returns the value of a number rounded to the nearest integer.
round(n: number): number

// Rounds down and returns the largest integer less than or equal to a given number
floor(n: number): number

// Returns the integer part of a number by removing any fractional digits.
trunc(n: number): number

// Returns the fractional part of a number
fract(n: number): number

// Returns the smallest of the numbers given as input parameters,
// or `Infinity` if there are no parameters.
// example: min(-10, 15, -1) returns -10
min(...ns: number): number

// Returns the largest of the numbers given as input parameters,
// or `-Infinity` if there are no parameters.
// example: max(-10, 15, -1) returns 15
max(...ns: number): number

// Returns the value of a base raised to a power
// example: pow(2, 3) returns 2³ or 8
pow(x: number, y: number): number

// Returns E (Euler's number) raised to the power of a number
// example: exp(1) returns 2.7182... (approximately)
exp(n: number): number

// Returns the square root of a number
sqrt(n: number): number

// Returns 1 or -1, indicating the sign of a number.
// If the number is 0, it will returns 0.
sign(n: number): number

// check a collision between two rectangles
// all arguments are required and must be numbers
colrect(x1, y1, w1, h1, x2, y2, w2, h2): boolean

// check a collision between two circles
// all arguments are required and must be numbers
colcirc(x1, y1, r1, x2, y2, r2): boolean

Variables

// the game canvas
CANVAS: HTMLCanvasElement

// the game screen width
WIDTH: number

// the game screen height
HEIGHT: number

// the center X of game screen
CENTERX: number

// the center Y of game screen
CENTERY: number

// the FPS meter
FPS: number

// the fixed delta time
DT: number

// the amount of time since the game started
ELAPSED: number

// `true` when the screen is touched/clicked
TAPPED: boolean

// `true` while the screen is being touched/clicked
TAPPING: boolean

// the tap/click X position
TAPX: number

// the tap/click Y position
TAPY: number

// Math constants
PI: number // approximately 3.14159 radians (180º)

TWO_PI: number // approximately 6.28318 radians (360º)

HALF_PI: number // approximately 1.57079 radians (90º)

Plugin API

// loads a plugin
// see: https://github.com/litecanvas/game-engine/blob/main/samples/plugin-basics/plugin-basics.js
use(callback): object|void

// create or update variables
setvar(name: string, value: any): void

// get the color value
getcolor(index: number): string

// add a game loop listener
// returns a function that removes the listener
listen(event: string, callback: function, highPriority = false): function

// resizes the game canvas
// also, emit the "resized" event
resize(width: number, height: number): void

Advanced Features (playground only)

// the plugin "Asset Loader" is automatically loaded into the playground
// see: https://github.com/litecanvas/plugin-asset-loader

Useful tools