simply2d
v1.4.1
Published
2D graphics and audio library for node.js
Maintainers
Readme
Simply2D
Introduction
This library for nodejs allows you, thanks to SDL2, to create windows and draw on the screen.
Installation
You can install this library using npm i simply2d. Node.js 22.22.2+, 24.15.0+, or 26+ is required.
This library require SDL2 in order to run. Simple DirectMedia Layer is a cross-platform library designed to provide low level access to different resources such as video. SDL2 is available for windows, linux and macos as well.
For Windows
Visual Studio VC tools are required. For more, see https://github.com/nodejs/node-gyp#readme
For Linux
To use Simply2D you must have installed make, a C++17 compiler, Python 3, pkg-config and the SDL2 development packages. To install SDL2 you can use the following command:
- For Debian and Ubuntu:
sudo apt install build-essential python3 pkg-config libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev - For Red Hat and Fedora:
sudo dnf install gcc-c++ make python3 pkgconf-pkg-config SDL2-devel SDL2_image-devel SDL2_ttf-devel SDL2_mixer-devel - For Arch Linux:
sudo pacman -S --needed base-devel python pkgconf sdl2 sdl2_image sdl2_ttf sdl2_mixer
If you encounter any problems, it is recommended to install the latest version of python3 and run
python3 -m pip install setuptoolsor justpip install setuptools
For contributors
Windows x64 SDL runtime and import libraries are included in npm releases. The local bin/ directory is ignored by Git. Before packing a release, populate it with the official SDL 2.32.10, SDL_image 2.8.12, SDL_ttf 2.24.0, and SDL_mixer 2.8.2 VC x64 libraries and their upstream licenses; CI downloads these automatically. Visual Studio C++ build tools and Python are still required to compile the Node addon.
Run npm install, then npm run build. Run npm test for the collision, animation, framebuffer, window-event, and audio smoke tests. CI also builds on Windows and installs the packed npm release into a separate project.
API
Canvas
The Canvas class allows you to create a canvas and to draw on it
import { Canvas } from "simply2d";
const canvas = new Canvas(
"my canvas", // window title
600, // window width
400, // window height
);You can specify other window options
const canvas = new Canvas("title", 200, 400, 0, 0, {
mode: "fullscreen",
resizable: false,
scale: 2,
antiAliasing: true
})Canvas.show
show(): voidShow the window
Canvas.hide
hide(): voidHide the window
Canvas.setBackgroundColor
setBackgroundColor(color: RGBAColor): voidSet the background color. An RGBAColor is an object that contains red, green, blue and alpha properties.
Canvas.sleep
sleep(ms: number): voidSleep ms milliseconds
Canvas.drawPoint
drawPoint(color: RGBAColor, position: Position): voidDraw a point on the screen. Position is an object with the x and y properties.
Canvas.drawLine
drawLine(color: RGBAColor, from: Position, to: Position): voidDraw a line from from coordinates to to coordinates
Canvas.drawRectangle
drawRectangle(color: RGBAColor, pos: Position, width: number, height: number, fill?: boolean): voidDraw a rectangle in the canvas
get Canvas.width
get width(): numberReturn the window width
get Canvas.height
get height(): numberReturn the window height
Canvas.clear
clear(): voidClear the screen
Canvas.loadRawData
loadRawData(pixels: Uint8Array, bitPerPixel: 8 | 16 | 24 | 32): voidWrite directly into the video buffer
Canvas.loadPNG
loadPNG(filename: string): voidWrite an PNG image into the canvas
Canvas.loadJPG
loadJPG(filename: string): voidWrite a JPG image into the canvas
Canvas.dumpPNG
dumpPNG(filename: string): voidSave the canvas as a PNG file
Canvas.dumpJPG
dumpJPG(filename: string): voidSave the canvas as a JPG file
Canvas.getScale
getScale(): numberReturn the scale factor
Canvas.resize
resize(width: number, height: number): voidResize the window in logical canvas pixels. Existing canvas and layer pixels are preserved.
Canvas.onClick
onClick(callback: (x: number, y: number) => void): voidOn click event
Canvas.onKeyDown
onKeyDown(callback: (key: Key) => void): voidOn key down event
Canvas.onKeyUp
onKeyUp(callback: (key: Key) => void): voidOn key up event
Canvas.initRenderSequence
initRenderSequence(): voidIt is used to initialize the rendering sequence. Every drawing process will not be displayed until exposeRender is called
Canvas.exposeRender
exposeRender(): voidShows rendering
Canvas.waitFrame
waitFrame(): voidSleep for a certain time before the next frame is rendered
Canvas.loop
loop(callback: (deltaMs: number) => void, options?: LoopOptions): voidStart the rendering loop. The callback receives elapsed milliseconds. Drawing is displayed once per frame. Defaults to 60 fps and limits elapsed time to 100 ms. Use clear: false to keep the previous frame.
Canvas.batch
batch(callback: () => void): voidDraw synchronously and display once when the callback finishes. Nested batches share the same display update.
Canvas.onKeysDown
onKeysDown(callback: (key: Key[]) => void): voidOn keys down event
Canvas.onKeysUp
onKeysUp(callback: (key: Key[]) => void): voidOn keys up event
Canvas.loadFont
loadFont(fontName: string, filePath: string): voidLoad a new font
Canvas.drawText
drawText(text: string, fontName: string, size: number, color: RGBAColor, start: Position): voidDraw text on the canvas
Canvas.drawArc
drawArc(color: RGBAColor, center: Position, radius: number, startingAngle: number, endingAngle: number): voidDraw an arc
Canvas.convertPolarCoords
static convertPolarCoords(center: Position, angle: number, radius: number): PositionConvert polar coordinates into x, y coordinates
Canvas.loadTexture
loadTexture(textureID: string, filePath: string): voidLoad a new texture from the specified file
Canvas.loadSVG
loadSVG(textureID: string, source: string | Uint8Array, options?: SVGOptions): voidLoad an SVG file or SVG bytes as a texture. Omit dimensions for the original size, or supply one dimension to preserve the aspect ratio. Rasterization happens when loading. Requires SDL_image 2.6.0 or later.
Canvas.drawTexture
drawTexture(textureID: string, pos: Position, options?: TextureDrawOptions): voidDraw a previously loaded texture. Options control cropping, size, rotation, flips, opacity and filtering. Nearest filtering is used by default.
Canvas.unloadTexture
unloadTexture(textureID: string): voidRelease a loaded texture.
Canvas.drawAnimation
drawAnimation(animation: SpriteAnimation, pos: Position, options?: Omit<TextureDrawOptions, "source">): voidDraw the current animation frame. Call animation.update(deltaMs) separately to advance playback.
Canvas.getScreenResolution
static getScreenResolution(): ResolutionGet the screen resolution
Canvas.getTextureResolution
getTextureResolution(textureID: string): ResolutionGet the resolution of a previously loaded texture
Canvas.drawPath
drawPath(path: Path, pos?: Position, color?: RGBAColor)Draw a path
Canvas.addLayer
addLayer(layerId: string): voidAdd a new layer
Canvas.removeLayer
removeLayer(layerId: string): voidRemove layer
Canvas.changeLayer
changeLayer(layerId: string): voidChange current layer
Canvas.useMainLayer
useMainLayer(): voidChange to the main default layer
get Canvas.frameTime
get frameTime(): numberGet current frame time, only if the scene is rendered with loop
get Canvas.fps
get fps(): numberGet the current frames per second, only if the scene is rendered with loop
Canvas.getLayers
getLayers(): Layer[]Get layers in order of appearance
Canvas.activateLayer
activateLayer(layerID: string): voidActivate a layer
Canvas.deactivateLayer
deactivateLayer(layerID: string): voidDeactivate a layer
get Canvas.antialiasing
get antialiasing(): booleanGet antialiasing flag
set Canvas.antialiasing
set antialiasing(): voidSet antialiasing flag
Canvas.clearAll
clearAll(): voidClear all layers, including the main layer
Canvas.moveLayer
moveLayer(layerID: string, direction: "up" | "down", steps: number = 1): voidChange layer rendering priority
Canvas.attach
attach(buffer: Uint8Array, bitPerPixel: PixelFormat): voidAttach a buffer to the video memory. The loop and every other drawing functions will be disabled.
Canvas.detach
detach(): voidWrite the final buffer changes to the canvas and detach it from the video memory
Canvas.requestClose
requestClose(): voidRequest to close the window. Returning false from an onWindowClose handler cancels the request. close() closes immediately.
Canvas.close
close(): voidClose the window
Canvas.endLoop
endLoop(): voidTerminate the current loop
get Canvas.mousePosition
get mousePosition(): PositionReturn the current mouse position
Canvas.applyFilter
applyFilter(fn: (value: number, index: number, buffer: Uint8Array) => number): voidApply a callback to every byte of the current rendering target and display the result. The callback receives the byte value, byte index, and buffer. Updates happen in place, in index order; returned values are converted to unsigned bytes. This stops the render loop, like attach. Detach any existing buffer first. The temporary buffer is always detached, including when the callback throws.
canvas.applyFilter(value => Math.floor(value / 2));Canvas.pollEvents
pollEvents(): voidProcess pending window and input events. The rendering loop calls this automatically.
Canvas.onWindowEvent
onWindowEvent(type: WindowEventType, callback: WindowEventHandler): () => voidRegister a window event handler. The returned function removes the handler. Events refer to the canvas window.
Canvas.onWindowResize
onWindowResize(callback: (width: number, height: number) => void): () => voidOn window resize. Width and height are in logical canvas pixels. The returned function removes the handler.
Canvas.onWindowMove
onWindowMove(callback: (x: number, y: number) => void): () => voidOn window move. Coordinates are in screen pixels. The returned function removes the handler.
Canvas.onWindowFocus
onWindowFocus(callback: () => void): () => voidOn window focus. The returned function removes the handler.
Canvas.onWindowUnfocus
onWindowUnfocus(callback: () => void): () => voidOn window focus lost. The returned function removes the handler.
Canvas.onWindowMinimize
onWindowMinimize(callback: () => void): () => voidOn window minimized. The returned function removes the handler.
Canvas.onWindowMaximize
onWindowMaximize(callback: () => void): () => voidOn window maximized. The returned function removes the handler.
Canvas.onWindowRestore
onWindowRestore(callback: () => void): () => voidOn window restored. The returned function removes the handler.
Canvas.onWindowShow
onWindowShow(callback: () => void): () => voidOn window shown. The returned function removes the handler.
Canvas.onWindowHide
onWindowHide(callback: () => void): () => voidOn window hidden. The returned function removes the handler.
Canvas.onWindowMouseEnter
onWindowMouseEnter(callback: () => void): () => voidOn mouse entering the window. The returned function removes the handler.
Canvas.onWindowMouseLeave
onWindowMouseLeave(callback: () => void): () => voidOn mouse leaving the window. The returned function removes the handler.
Canvas.onWindowClose
onWindowClose(callback: () => boolean | void): () => voidOn window close requested. Return false to cancel closing. The returned function removes the handler.
Canvas options
type CanvasOptions = {
mode?: "fullscreen" | "minimized" | "maximized" | "hidden" | "shown",
resizable?: boolean,
scale?: number,
antiAliasing?: boolean,
removeWindowDecoration?: boolean,
vsync?: boolean
}Set resizable to true to allow window resizing. Non-resizable canvases keep their logical size unless resize() is called. Set vsync to false to disable vertical synchronization.
Canvas constant positions
It is possible to access constant positions relative to the size of the canvas. Example:
import { Canvas, Colors } from "simply2d"
const canvas = new Canvas("myCanvas", 200, 200);
canvas.drawLine(Colors.BLUE, canvas.TOP_LEFT /* the top left corner */, canvas.BOTTOM_RIGHT /* the bottom right corner */);SpriteSheet
A sprite sheet stores a regular grid of frames. Indexes run from left to right, then down.
import { SpriteSheet } from "simply2d";
const sheet = new SpriteSheet("player", 16, 16, 4, 2);The constructor takes the texture ID, frame width, frame height, columns and rows. Load the texture with Canvas.loadTexture first.
SpriteSheet.frame
frame(index: number): RectangleReturn the source rectangle for a frame.
SpriteSheet.animation
animation(indexes: readonly number[], options?: AnimationOptions): SpriteAnimationCreate an animation from frame indexes.
SpriteAnimation
An animation stores source rectangles and playback timing.
import { SpriteAnimation } from "simply2d";
const walk = new SpriteAnimation("player", [
{ x: 0, y: 0, width: 16, height: 16 },
{ x: 16, y: 0, width: 16, height: 16 }
], { fps: 10 });
canvas.loop(deltaMs => {
walk.update(deltaMs);
canvas.drawAnimation(walk, { x: 40, y: 60 });
});get SpriteAnimation.frame
get frame(): Readonly<Rectangle>Return the current source rectangle.
get SpriteAnimation.frameIndex
get frameIndex(): numberReturn the current frame index.
get SpriteAnimation.isPlaying
get isPlaying(): booleanReturn whether the animation is playing.
get SpriteAnimation.finished
get finished(): booleanReturn whether a non-looping animation has finished.
SpriteAnimation.update
update(deltaMs: number): voidAdvance playback by elapsed milliseconds. Update once per frame, even when drawing the animation more than once.
SpriteAnimation.play
play(restart?: boolean): voidResume playback. Set restart to true to start from the first frame. Finished animations restart automatically.
SpriteAnimation.pause
pause(): voidPause playback on the current frame.
SpriteAnimation.stop
stop(): voidStop playback and return to the first frame.
SpriteAnimation.reset
reset(): voidReturn to the first frame without changing whether playback is paused.
Audio
Audio uses SDL_mixer to play WAV, MP3, OGG and FLAC files. One Audio instance can be open at a time, with 32 sound effects and one music track playing together.
import { Audio } from "simply2d";
const audio = new Audio();
audio.loadSound("jump", "jump.wav");
audio.play("jump");
audio.loadMusic("theme", "theme.ogg");
audio.playMusic("theme", { loop: true });SDL_mixer 2.6.0 or later is required. Sound effects are loaded into memory; music is streamed from files. Playback does not keep the Node.js event loop alive.
Audio.loadSound
loadSound(id: string, source: string | Uint8Array): numberLoad a sound from a file or encoded audio bytes. Return its duration in seconds. Replacing an ID affects future playback; existing instances keep their original sound.
Audio.getSoundDuration
getSoundDuration(id: string): numberReturn the duration of a loaded sound in seconds.
Audio.play
play(id: string, options?: SoundOptions): SoundPlaybackPlay a loaded sound and return its playback controls. Each call creates a separate playback instance. Throws when all 32 sound channels are in use.
Audio.unloadSound
unloadSound(id: string): voidStop playback instances of the loaded sound and release it.
Audio.loadMusic
loadMusic(id: string, filename: string): voidLoad a music file for streaming.
Audio.playMusic
playMusic(id: string, options?: SoundOptions): SoundPlaybackPlay a loaded music track and return its playback controls. Replaces the current track.
Audio.unloadMusic
unloadMusic(id: string): voidRelease a loaded music track. Stop it if it is playing.
get Audio.volume
get volume(): numberReturn the master volume.
set Audio.volume
set volume(value: number)Set the volume of music and sound effects, from 0 to 1. Defaults to 1.
get Audio.paused
get paused(): booleanReturn whether all audio is paused.
Audio.pause
pause(): voidPause music and sound effects.
Audio.resume
resume(): voidResume audio. Instances paused individually remain paused.
Audio.stopAll
stopAll(): voidStop music and all sound effects.
Audio.close
close(): voidStop playback and release the audio device. Closing a canvas does not close audio.
get Audio.closed
get closed(): booleanReturn whether the audio device is closed.
SoundPlayback
Playback controls returned by Audio.play and Audio.playMusic.
const sound = audio.play("jump", { volume: 0.5 });
sound.pause();
sound.resume();
sound.stop();get SoundPlayback.state
get state(): PlaybackStateReturn "playing", "paused" or "stopped".
get SoundPlayback.isPlaying
get isPlaying(): booleanReturn whether this instance is playing.
get SoundPlayback.volume
get volume(): numberReturn the instance volume.
set SoundPlayback.volume
set volume(value: number)Set the instance volume, from 0 to 1. The master volume also applies.
SoundPlayback.pause
pause(): voidPause this playback instance.
SoundPlayback.resume
resume(): voidResume this playback instance.
SoundPlayback.stop
stop(): voidStop this playback instance.
rectanglesOverlap
rectanglesOverlap(a: Rectangle, b: Rectangle, touching?: boolean): booleanReturn whether two axis-aligned rectangles overlap. Set touching to true to count touching edges. Defaults to false.
rectangleIntersection
rectangleIntersection(a: Rectangle, b: Rectangle): Rectangle | nullReturn the overlap rectangle, or null when separated or only touching.
rectangleContact
rectangleContact(a: Rectangle, b: Rectangle): RectangleContact | nullReturn the smallest axis-aligned translation needed to move the first rectangle out of the second, or null when they do not overlap. Inputs are not changed.
pointInRectangle
pointInRectangle(point: Position, rect: Rectangle, touching?: boolean): booleanReturn whether a point is inside a rectangle. Boundaries count by default; set touching to false to exclude them.
circlesOverlap
circlesOverlap(a: Circle, b: Circle, touching?: boolean): booleanReturn whether two circles overlap. Set touching to true to count touching edges. Defaults to false.
circleIntersectsRectangle
circleIntersectsRectangle(circle: Circle, rect: Rectangle, touching?: boolean): booleanReturn whether a circle overlaps an axis-aligned rectangle. Set touching to true to count touching edges. Defaults to false.
Collision functions use logical coordinates. Zero-size shapes do not collide. Rotated shapes and continuous motion are not supported; the Mario example uses small time steps for movement.
Colors
Colors is an object that contains different standard colors and some useful function
import { Canvas, Colors } from "simply2d";
const canvas = new Canvas("title", 100, 100);
canvas.setBackgroundColor(Colors.RED); // #FF0000 hex color
canvas.drawLine(
Colors.BLACK, // #000000 hex color
{
x: 0,
y: 0
},
{
x: canvas.getWidth(),
y: canvas.getHeight()
}
);Colors.from8bit
from8bit(color256: number): RGBAColorConvert an 8 bit color into a 24 bit color
Colors.from16bit
from16bit(color: number): RGBAColorConvert a 16 bit color into a 24 bit color
Colors.from24bit
from24bit(color: number): RGBAColorConvert a 24 bit color number into a 24 bit color RGBAColor object
Colors.from32bit
from32bit(color: number): RGBAColorConvert a 32 bit color number into a RGBAColor object
Position
Is a type for storing coordinates
import { Position } from "simply2d" // only in typescript
let cord: Position = {
x: 203,
y: 301
}RGBAColor
Used to save RGBA color values
import { RGBAColor } from "simply2d" // only in typescript
let color: RGBAColor = {
red: 255,
green: 255,
blue: 0,
alpha: 255
}Resolution
Used to save a pair of width and height values
import { Resolution } from "simply2d"
let res: Resolution = {
w: 1920,
h: 1080
}Path
A path is an object used to represent a polyline
import { Path } from "simply2d";
const p = new Path();
p.setStart({ x: 10, y: 15 });
p.pushLine({ x: 20, y: 60 });
p.close();PixelFormats
Static class that stores all the available pixel formats
PixelFormats.rgb332;
PixelFormats.rgb565;
PixelFormats.rgb888;
PixelFormats.rgba8888;Rectangle
type Rectangle = Position & { width: number, height: number };A rectangle with its position at the top left corner.
Circle
type Circle = Position & { radius: number };A circle with its position at the center.
RectangleContact
type RectangleContact = {
depth: number,
normal: Position,
translation: Position
};Collision depth, outward direction and the translation needed to separate the first rectangle from the second.
TextureDrawOptions
type TextureDrawOptions = {
source?: Rectangle,
width?: number,
height?: number,
rotation?: number,
flipX?: boolean,
flipY?: boolean,
opacity?: number,
filtering?: "nearest" | "linear"
};Source coordinates are in texture pixels. Rotation is in degrees and opacity ranges from 0 to 1. Defaults to the source size, no rotation or flips, full opacity and nearest filtering.
SVGOptions
type SVGOptions = {
width?: number,
height?: number
};SVG rasterization size in pixels. Dimensions must be positive integers. Supply one dimension to preserve the aspect ratio, or both for an explicit size.
LoopOptions
type LoopOptions = {
fps?: number,
maxDeltaMs?: number,
clear?: boolean
};Defaults to 60 fps, a maximum elapsed time of 100 ms and clearing the canvas each frame.
AnimationOptions
type AnimationOptions = {
fps?: number,
loop?: boolean,
autoplay?: boolean
};Defaults to 12 fps, looping and automatic playback. Set loop: false to play once.
SoundOptions
type SoundOptions = {
loop?: boolean,
volume?: number
};Defaults to no looping and volume 1. Volume ranges from 0 to 1.
PlaybackState
type PlaybackState = "playing" | "paused" | "stopped";Current state of a sound or music playback instance.
WindowEventType
type WindowEventType = "resize" | "focus" | "unfocus" | "move"
| "minimize" | "maximize" | "restore" | "show" | "hide"
| "mouseEnter" | "mouseLeave" | "close";Available canvas window events.
WindowEvent
type WindowEvent = {
type: WindowEventType,
width?: number,
height?: number,
x?: number,
y?: number
};Resize events provide logical width and height. Move events provide screen coordinates.
WindowEventHandler
type WindowEventHandler = (event: WindowEvent) => boolean | void;Callback for Canvas.onWindowEvent. Returning false from a close handler cancels closing.
