Pi.js Reference

Version: 2.1 (change)

addPalColors

Appends new colors to the current palette and returns their indices.

Syntax

addPalColors( colors );

Description

Parameters

  • colors (*Array)

    Array of colors to add (names, hex, RGB[A]).

Returns

  • *Array

    Array of indices for colors that were added to the palette.

Example

$.screen( "300x200" );
const indices = $.addPalColors( [ "#ee2233", "gold", [ 10, 200, 30 ] ] );
for( const i of indices ) {
	$.setColor( i );
	$.print( `Color: ${i}`, false, true );
}

See Also

applyShader

Queues an FBO shader at the current point in draw order.

Syntax

applyShader( shaderHandle, uniforms );

Description

Parameters

  • shaderHandle (number)

    Shader handle returned by createShader.

  • uniforms? (ShaderUniforms)

    Optional per-call uniform overrides for this invocation.

Returns

  • void

    This function does not return a value.

Example

const invert = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4(1.0 - color.rgb, color.a);
}` );

$.screen( "320x200" );
$.rect( 10, 10, 40, 40, 4 );
$.applyShader( invert );
$.line( 0, 0, 50, 50 );

See Also

arc

Draws an arc on the screen.

Syntax

arc( x, y, radius, angle1, angle2 );

Description

Parameters

  • x (number)

    The x coordinate of the center point of the arc's circle.

  • y (number)

    The y coordinate of the center point of the arc's circle.

  • radius (number)

    The radius of the arc's circle.

  • angle1 (number)

    The starting angle in degrees.

  • angle2 (number)

    The ending angle in degrees.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.arc( 150, 100, 50, 45, 270 );

See Also

bezier

Draws a bezier curve on the screen.

Syntax

bezier( x1, y1, x2, y2, x3, y3, x4, y4 );

Description

Parameters

  • x1 (number)

    The x coordinate of the first control point (starting point).

  • y1 (number)

    The y coordinate of the first control point (starting point).

  • x2 (number)

    The x coordinate of the second control point.

  • y2 (number)

    The y coordinate of the second control point.

  • x3 (number)

    The x coordinate of the third control point.

  • y3 (number)

    The y coordinate of the third control point.

  • x4 (number)

    The x coordinate of the fourth control point (ending point).

  • y4 (number)

    The y coordinate of the fourth control point (ending point).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.bezier( 15, 10, 45, 135, 195, 75, 280, 185 );

See Also

blitImage

Blits an image element directly onto the screen using replace batch mode.

Syntax

blitImage( img, x, y, color, anchorX, anchorY, scaleX, scaleY, angleRad );

Description

Parameters

  • img (*HTMLElement)

    Image or Canvas element to blit (not a name string).

  • x? (number)

    X (horizontal) coordinate (default 0).

  • y? (number)

    Y (vertical) coordinate (default 0).

  • color? (any)

    Optional color multiplier. Can be a palette index or color value (string, array, object, number). Defaults to white.

  • anchorX? (number)

    X (horizontal) rotation point (0.0-1.0). Defaults to screen's default anchor.

  • anchorY? (number)

    Y (vertical) rotation point (0.0-1.0). Defaults to screen's default anchor.

  • scaleX? (number)

    Scale factor X (default 1).

  • scaleY? (number)

    Scale factor Y (default 1).

  • angleRad? (number)

    Rotation angle in radians (default 0).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.loadImage( "media/player.png", "player" );
$.ready( () => {
	const img = $.getImage( "player" );
	$.blitImage( img, 150, 100, null, 0.5, 0.5, 1, 1, 0 );
} );

See Also

blitSprite

Blits a frame from a spritesheet onto the screen using replace batch mode.

Syntax

blitSprite( name, frame, x, y, color, anchorX, anchorY, scaleX, scaleY, angleRad );

Description

Parameters

  • name (string)

    Spritesheet name.

  • frame? (number)

    Frame index to draw (default 0).

  • x? (number)

    X (horizontal) coordinate (default 0).

  • y? (number)

    Y (vertical) coordinate (default 0).

  • color? (any)

    Optional color multiplier. Can be a palette index or color value (string, array, object, number). Defaults to white.

  • anchorX? (number)

    X (horizontal) rotation point (0.0-1.0). Defaults to screen's default anchor.

  • anchorY? (number)

    Y (vertical) rotation point (0.0-1.0). Defaults to screen's default anchor.

  • scaleX? (number)

    Scale factor X (default 1).

  • scaleY? (number)

    Scale factor Y (default 1).

  • angleRad? (number)

    Rotation angle in radians (default 0).

Returns

  • void

    This function does not return a value.

Example

$.screen( "128x80" );
$.loadSpritesheet( "media/tiles.png", "tiles", 16, 16, 0 );
let tilesData;
let pal;
$.ready( () => {
	pal = $.getPal();
	tilesData = $.getSpritesheetData( "tiles" );
	let keys = "0123456789abcdefghijkl";
	let keyMap = {};
	keys.split( "" ).forEach(
		( key, val ) => keyMap[ key ] = val
	);
	let map = [
		"00ijk0000",
		"00001222",
		"07008999",
		"0012c996",
		"e0899d99",
	];
	let x = 0;
	let y = 0;
	for( const row of map ) {
		const cols = row.split( "" );
		for( const tile of cols ) {
			const frame = keyMap[ tile ];
			$.blitSprite( "tiles", frame, x, y );
			x += 16;
		}
		x = 0;
		y += 16;
	}
} );

See Also

calcWidth

Calculates the pixel width of a text message.

Syntax

calcWidth( msg );

Description

Parameters

  • msg? (string)

    Text message to calculate width for. Defaults to empty string if not provided.

Returns

  • number

    Width of the text in pixels.

Example

$.screen( "320x200" );
$.setFont( 1 );
const width = $.calcWidth( "Hello World" );
$.print( `"Hello World" is ${width} pixels wide` );

See Also

circle

Draws a circle on the screen.

Syntax

circle( x, y, radius, fillColor );

Description

Parameters

  • x (number)

    The x coordinate of the center of the circle.

  • y (number)

    The y coordinate of the center of the circle.

  • radius (number)

    The radius of the circle.

  • fillColor? (any)

    The fill color for the circle. Can be a palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.circle( 150, 100, 50, "red" );

See Also

clearEvents

Clears events from all plugins or a specific plugin event type.

Syntax

clearEvents( type );

Description

Parameters

  • type? (string)

    Optional type to clear (e.g., "keyboard", "mouse", "touch", "press").

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Move mouse or touch to paint screen click/touch up to stop." );
$.onpress( "move", pressMove );
$.onpress( "up", pressStop );

// Press move function
function pressMove( data ) {
	$.setPosPx( data.x, data.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 8 );
	$.print( "+", true );
}

// Press stop function
function pressStop() {
	$.setColor( 14 );
	var pos = $.getPos();
	$.setPos( pos.col - 4, pos.row );
	$.print( "Stopped!", true );
	$.clearEvents();
}

See Also

cls

Clears the screen or a rectangular region.

Syntax

cls( x, y, width, height );

Description

Parameters

  • x? (number)

    The horizontal coordinate of the region to clear.

  • y? (number)

    The vertical coordinate of the region to clear.

  • width? (number)

    The width of the region to clear.

  • height? (number)

    The height of the region to clear.

Returns

  • void

    This function does not return a value.

Example

$.screen( "128x80" );
$.paint( 0, 0, 4 );
$.print( "The screen is red" );
$.cls();
$.print( "The screen is clear" );
$.paint( 0, 10, 1 );
$.print( "The screen is blue" );
$.cls( 0, 16, 128, 80 );
$.print( "The screen is partially clear" );

createImageFromScreen

Creates an image from a region of the current screen.

Syntax

createImageFromScreen( name, x1, y1, x2, y2 );

Description

Parameters

  • name? (string)

    Optional unique name for the image. Auto-generated if omitted.

  • x1? (number)

    Left coordinate (defaults to 0).

  • y1? (number)

    Top coordinate (defaults to 0).

  • x2? (number)

    Right coordinate (defaults to screen width - 1).

  • y2? (number)

    Bottom coordinate (defaults to screen height - 1).

Returns

  • string

    The created image name.

Example

$.screen( "300x200" );
$.filterImg( ( color, x, y ) => {
	color[ 0 ] = ( x * y ) % 255;
	color[ 1 ] = ( x * y * 2 ) % 255;
	color[ 2 ] = ( x * y * 3 ) % 255;
	color[ 3 ] = 255;
	return true;
}, 0, 0, 50, 50 );

// Wait a tick because filterImg happens at end of frame
setTimeout( () => {
	const image1 = $.createImageFromScreen( { "x1": 0, "y1": 0, "x2": 50, "y2": 50 } );
	$.createImageFromScreen( "image2", 15, 15, 35, 35 );
	$.drawImage( image1, 100, 0 );
	$.drawImage( "image2", 200, 0 );
}, 0 );

See Also

createShader

Creates a custom fragment shader and returns a handle.

Syntax

createShader( fragmentSource, uniforms );

Description

Parameters

  • fragmentSource (string)

    GLSL ES 3.00 fragment shader source. Must include "#version 300 es".

  • uniforms? (ShaderUniforms)

    Optional reflected custom uniform values keyed by uniform name.

Returns

  • number

    Shader handle id for applyShader or setDisplayShader.

Example

const invert = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4(1.0 - color.rgb, color.a);
}` );

$.screen( "320x200" );
$.rect( 10, 10, 40, 40, 11 );
$.applyShader( invert );
$.line( 0, 0, 50, 50 );

See Also

draw

Draws lines on the screen defined by a string.

Syntax

draw( drawString );

Description

Parameters

  • drawString (string)

    Case insensitive string containing draw commands.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.pset( 150, 100 );
$.draw( "C2 R15 D15 L30 U15 R15" );				// Draw House
$.draw( "B G4 C1 L6 D6 R6 U6 BG3 P1" ); 		// Draw Window
$.draw( "B E3 B R14 C1 L6 D6 R6 U6 BG3 P1" ); 	// Draw Window
$.draw( "B E3 B R1 P2" );						// Paint House
$.draw( "B E4 B U C6 H15 G15 B R5 P6" );		// Draw Roof

See Also

drawImage

Draws an image onto the screen.

Syntax

drawImage( image, x, y, color, anchorX, anchorY, scaleX, scaleY, angle );

Description

Parameters

  • image (any)

    Image name (string), url (string), screen object, or Image/Canvas element.

  • x (number)

    X (horizontal) coordinate.

  • y (number)

    Y (vertical) coordinate.

  • color? (any)

    Optional color multiplier. Can be a palette index or color value (string, array, object, number).

  • anchorX? (number)

    X (horizontal) rotation point (0.0-1.0).

  • anchorY? (number)

    Y (vertical) rotation point (0.0-1.0).

  • scaleX? (number)

    Scale factor X (default 1).

  • scaleY? (number)

    Scale factor Y (default 1).

  • angle? (number)

    Rotation angle in degrees (default 0).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.loadImage( "media/player.png", "player" );
$.ready( () => {
	$.drawImage( "player", 150, 100, null, 0.5, 0.5, 1, 1, 0 );
} );

See Also

drawSprite

Draws a frame from a spritesheet onto the screen.

Syntax

drawSprite( name, frame, x, y, color, anchorX, anchorY, scaleX, scaleY, angle );

Description

Parameters

  • name (string)

    Spritesheet name.

  • frame? (number)

    Frame index to draw (default 0).

  • x (number)

    X (horizontal) coordinate.

  • y (number)

    Y (vertical) coordinate.

  • color? (any)

    Optional color multiplier. Can be a palette index or color value (string, array, object, number).

  • anchorX? (number)

    Anchor X (0.0-1.0). Defaults to screen's default anchor.

  • anchorY? (number)

    Anchor Y (0.0-1.0). Defaults to screen's default anchor.

  • scaleX? (number)

    Scale factor X (default 1).

  • scaleY? (number)

    Scale factor Y (default 1).

  • angle? (number)

    Rotation angle in degrees (default 0).

Returns

  • void

    This function does not return a value.

Example

$.screen( "150x100" );
$.loadSpritesheet( "media/cat_sprite.png", "cat", 34, 34, 1 );
let catData;
$.ready( () => {
	catData = $.getSpritesheetData( "cat" );
	requestAnimationFrame( animate );
} );

function animate( t ) {
	$.cls();
	const frame = Math.round( t / 100 ) % catData.frameCount;
	$.drawSprite( "cat", frame, 75, 50, null, 0.5, 0.5 );
	requestAnimationFrame( animate );
}

See Also

ellipse

Draws an ellipse on the screen.

Syntax

ellipse( x, y, radiusX, radiusY, fillColor );

Description

Parameters

  • x (number)

    The x coordinate of the center of the ellipse.

  • y (number)

    The y coordinate of the center of the ellipse.

  • radiusX (number)

    The horizontal radius of the ellipse.

  • radiusY (number)

    The vertical radius of the ellipse.

  • fillColor? (any)

    The fill color for the ellipse. Can be a palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.ellipse( 150, 100, 50, 80, "blue" );

See Also

filterImg

Applies a filter function to a rectangular region of the screen.

Syntax

filterImg( filter, x1, y1, x2, y2 );

Description

Parameters

  • filter (function)

    Callback (color, x, y) => truthy to accept modified pixel color, falsy to skip.

  • x1? (number)

    Left coordinate (default 0).

  • y1? (number)

    Top coordinate (default 0).

  • x2? (number)

    Right coordinate (default screen width - 1).

  • y2? (number)

    Bottom coordinate (default screen height - 1).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.circle( 150, 100, 50, "red" );
$.filterImg( function ( color, x, y ) {
	color[ 0 ] = color[ 0 ] - Math.round( Math.tan( ( x + y ) / 10 ) * 128 );
	color[ 1 ] = color[ 1 ] + Math.round( Math.cos( x / 7 ) * 128 );
	color[ 2 ] = color[ 2 ] + Math.round( Math.sin( y / 5 ) * 128 );
	return color;
} );

See Also

get

Reads a region of pixels as indices (default) or color values.

Syntax

get( x, y, width, height, tolerance, asIndex );

Description

Parameters

  • x (number)

    Left coordinate.

  • y (number)

    Top coordinate.

  • width (number)

    Region width.

  • height (number)

    Region height.

  • tolerance? (number)

    Color matching tolerance [0.0-1.0] for index conversion (default 1).

  • asIndex? (boolean)

    If false (default true), return color value objects instead of indices.

Returns

  • *Array

    2D array [height][width] of palette indices (default) or color values.

Example

$.screen( "300x200" );
$.circle( 150, 110, 50, 4 );

// Get indices
const indices = $.get( 105, 85, 5, 5 );
$.print( "indices = [" );
for( let i = 0; i < indices.length; i++ ) {
	$.print( "    [ " + indices[ i ].join( ", " ) + " ]," );
}
$.print( "]" );

// Get color values
const colorNames = {
	"rgba(0, 0, 0, 0)": "black",
	"rgba(170, 170, 170, 255)": "gray",
	"rgba(170, 0, 0, 255)": "red",
};
const mapColors = c => colorNames[ `rgba(${c.array.join( ", " )})` ];
const colors = $.get( 105, 85, 5, 5, 1, false );
$.setPos( 0, 15 );
$.print( "colors = [" );
for( let i = 0; i < colors.length; i++ ) {
	$.print( "    [ " +
		colors[ i ].map( mapColors ).join( ", " ) + " ],"
	);
}
$.print( "]" );
$.put( indices, 20, 80 );

See Also

getAsync

Asynchronously reads a region of pixels as indices (default) or color values.

Syntax

getAsync( x, y, width, height, tolerance, asIndex );

Description

Parameters

  • x (number)

    Left coordinate.

  • y (number)

    Top coordinate.

  • width (number)

    Region width.

  • height (number)

    Region height.

  • tolerance? (number)

    Color matching tolerance [0.0-1.0] for index conversion (default 1).

  • asIndex? (boolean)

    If false, resolve to color value objects instead of indices.

Returns

  • *Promise

    Promise resolving to 2D array [height][width] of indices (default) or color values.

Example

$.screen( "300x200" );
$.circle( 150, 110, 50, 4 );

getStuff( true );
getStuff( false );

async function getStuff( asIndex ) {

	// Color value names
	const colorNames = {
		"rgba(0, 0, 0, 0)": "black",
		"rgba(170, 170, 170, 255)": " gray",
		"rgba(170, 0, 0, 255)": "  red",
	};
	const mapColors = c => colorNames[ `rgba(${c.array.join( ", " )})` ];

	// Get stuff
	const stuffName = asIndex ? "indices" : "colors";
	const stuff = await $.getAsync( 105, 85, 5, 5, 1, asIndex );
	$.print( `${stuffName} = [` );
	for( let i = 0; i < stuff.length; i++ ) {
		if( asIndex ) {
			$.print( `	[ ${stuff[ i ].join( ", " )} ],` );
		} else {
			$.print( `	[ ${stuff[ i ].map( mapColors ).join( ", " )} ],` );
		}
	}
	$.print( "]" );

	if( asIndex ) {
		$.put( stuff, 80, 85 );
		$.print( "\n\n\n\n\n\n" );
	}
}

See Also

getAvailableFonts

Returns an array of all loaded fonts with their properties.

Syntax

getAvailableFonts();

Description

Returns

  • *Array

    Array of font info objects with id, width, and height properties.

Example

$.screen( "300x200" );
const fonts = $.getAvailableFonts();
for( const font of fonts ) {
	$.setFont( font.id );
	$.print( `Font ${font.id}: ${font.width}x${font.height}\n` );
}

See Also

getColor

Gets the current foreground color.

Syntax

getColor( asIndex );

Description

Parameters

  • asIndex? (boolean)

    If true returns the palette index, otherwise returns a color value object.

Returns

  • *Many

    Palette index if asIndex is true; otherwise a color value object.

Example

$.screen( "300x200" );
$.setColor( 2)
$.print( `Current Color Index: ${$.getColor( true )}` );
$.print( `Current Color Value: [${$.getColor( false ).array.join( ", " )}]` );

See Also

getDefaultPal

Gets default palette and returns an array with all the color data. The default color palette defines what colors are available when a new screen is created.

Syntax

getDefaultPal();

Returns

  • *Array

    An array of color data for the default color palette.

Example

$.screen( "300x200" );
var pal = $.getDefaultPal();
$.setColor( 4 );
$.print( `Color 4 in default pal = [ ${pal[ 4 ].array.join( ", " )} ]` );

See Also

getImage

Gets the image element by name.

Syntax

getImage( name );

Description

Parameters

  • name (string)

    Image name.

Returns

  • *HTMLElement

    The actual Image or Canvas element.

Example

$.screen( "300x200" );
$.loadImage( "media/player.png", "player" );
$.ready( () => {
	const img = $.getImage( "player" );
	$.drawImage( img, 150, 100, null, 0.5, 0.5, 1, 1, 0 );
} );

See Also

getPal

Returns the current color palette as an array.

Syntax

getPal( include0 );

Description

Parameters

  • include0? (boolean)

    If true include palette index 0 (transparent black).

Returns

  • *Array

    Array of color value objects representing the current screen palette.

Example

$.screen("300x200");
var pal = $.getPal();
$.setColor( 2 );

// Note pal[ 1 ] = $.setColor( 2 ) because of the missing 0 index from $.getPal.
$.print( "[ " + pal[ 1 ].array.join( ", " ) + " ]" );

See Also

getPalColor

Returns the color value object for a palette index.

Syntax

getPalColor( index );

Description

Parameters

  • index (number)

    Palette index to retrieve.

Returns

  • *PiColor

    Color value object if found; otherwise null.

Example

$.screen( "300x200" );
const color = $.getPalColor( 2 );
$.setColor( color );
$.print( "Color 2 = [" + color.array.join( ", " ) + "]" );

See Also

getPalIndex

Finds the palette index for a color with optional tolerance.

Syntax

getPalIndex( color, tolerance );

Description

Parameters

  • color (any)

    Palette index or color value (string, array, object, number).

  • tolerance? (number)

    Number between 0 and 1 indicating acceptable color difference.

Returns

  • *number

    Palette index if a match is found; otherwise null.

Example

$.screen( "300x200" );
const idx = $.getPalIndex( "#FF0000", 0.25 );
$.setColor( idx );
$.print( "Color Index = " + idx );

See Also

getPixel

Reads the color of a single pixel.

Syntax

getPixel( x, y, asIndex );

Description

Parameters

  • x (number)

    X (horizontal) coordinate.

  • y (number)

    Y (vertical) coordinate.

  • asIndex? (boolean)

    If true, return palette index instead of color value.

Returns

  • *Many

    Palette index if asIndex is true; otherwise a color value object.

Example

$.screen( "300x200" );
$.circle( 150, 100, 50, "blue" );
const color = $.getPixel( 150, 100 );
$.print( `Circle fill color: [${color.array.join( ", " )}]` );
const idx = $.getPixel( 150, 100, true );
$.print( `Circle fill color index: ${idx}` );

See Also

getPixelAsync

Asynchronously reads the color of a single pixel.

Syntax

getPixelAsync( x, y, asIndex );

Description

Parameters

  • x (number)

    X (horizontal) coordinate.

  • y (number)

    Y (vertical) coordinate.

  • asIndex? (boolean)

    If true, resolve to palette index instead of color value.

Returns

  • *Promise

    Promise that resolves to palette index or color value object.

Example

$.screen( "300x200" );
$.circle( 150, 100, 50, "blue" );
getCircleFillColor();

async function getCircleFillColor() {
	const color = await $.getPixelAsync( 150, 100 );
	$.print( `Circle fill color: [${color.array.join( ", " )}]` );
	const idx = await $.getPixelAsync( 150, 100, true );
	$.print( `Circle fill color index: ${idx}` );
}

See Also

getPlugins

Returns a list of registered plugins and their status.

Syntax

getPlugins();

Description

Returns

  • *Array

    Array of plugin info objects: { name, version, description, initialized }.

Example

const plugins = $.getPlugins();
$.screen( "300x200" );
for( const plugin of plugins ) {
	$.print( `Plugin:      ${plugin.name} (${plugin.version})` );
	$.print( `Description: ${plugin.description}` );
	$.print();
}

See Also

getScreen

Gets a screen API object by screen ID.

Syntax

getScreen( screenId );

Description

Parameters

  • screenId (number)

    The screen ID to retrieve.

Returns

  • Screen

    Screen API object with all graphics commands and screen=true and id property.

Example

$.screen( "320x200" );
$.screen( "320x200" );
const screen0 = $.getScreen( 0 );
screen0.print( `Screen: ${screen0.id}` );
const screen1 = $.getScreen( 1 );

// Set screen1 to have a transparent background so it doesn't cover screen 0
screen1.setBgColor( 0 );
screen1.setPosPx( 0, 100 );
screen1.print( `Screen: ${screen1.id}` );
$.print( "Active Screen" );

See Also

getShaderInfo

Returns lifecycle and reflection diagnostics for a custom shader.

Syntax

getShaderInfo( shaderHandle );

Description

Parameters

  • shaderHandle (number)

    Shader handle returned by createShader.

Returns

  • ShaderInfo

    Copied shader lifecycle and diagnostic information.

Example

const invert = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
uniform float u_gain;
uniform vec3 u_tint;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4((1.0 - color.rgb) * u_tint * u_gain, color.a);
}`, {
	"u_gain": 0.75,
	"u_tint": [ 1, 0.8, 0.6 ]
} );

$.screen( "640x480" );
$.circle( 320, 240, 80, "red" );
$.applyShader( invert, { "u_gain": 0.5 } );
const info = $.getShaderInfo( invert );

$.setFont( 3 );
$.print( `Shader: ${info.id}` );
$.print();
$.print( "Source:" );
$.print( info.fragmentSource );
$.print();
$.print( "Default uniforms:" );
$.print( `  u_gain: ${info.uniforms.u_gain}` );
$.print( `  u_tint: ${info.uniforms.u_tint.join( ", " )}` );
$.print();
$.print( `Compiled screens: ${info.compiledScreenCount}` );
$.print( `Queued passes: ${info.queuedPassCount}` );
$.print( `Display screens: ${info.displayScreenCount}` );
$.print();
if( info.screen ) {
	$.print( "Current screen:" );
	$.print( `  Compiled: ${info.screen.compiled}` );
	$.print( `  Queued passes: ${info.screen.queuedPassCount}` );
	$.print( `  Display active: ${info.screen.displayActive}` );
	$.print( "  Reflected uniforms:" );
	for( const uniform of info.screen.uniforms ) {
		$.print( `    ${uniform.name}: ${uniform.type}, size ${uniform.size}, ` +
			`reserved ${uniform.reserved}` );
	}
}

See Also

getSpritesheetData

Returns frame metadata for a spritesheet.

Syntax

getSpritesheetData( name );

Description

Parameters

  • name (string)

    Spritesheet name.

Returns

  • SpritesheetData

    Object with frameCount and frames array (index, x, y, width, height, left, top, right, bottom).

Example

$.screen( "300x200" );
$.loadSpritesheet( {
	"src": "media/cat_sprite.png",
	"name": "cat",
	"width": 34,
	"height": 34,
	"margin": 1
} );
$.ready( () => {
	const data = $.getSpritesheetData( { "name": "cat" } );
	$.print( `Cat sprite has ${data.frameCount} frames` );
} );

See Also

height

Returns the screen or active view height in pixels.

Syntax

height();

Description

Returns

  • number

    Screen or local view height in pixels.

Example

$.screen( "320x200" );
const h = $.height();
$.print( `Screen Height: ${h}` );
$.print( `Canvas CSS height: ${$.canvas().offsetHeight}` );
$.pushView( 30, 20, 50, 50 );
$.print( `Viewport Height: ${$.height()} ` );
$.popView();

See Also

ingamepad

Gets gamepad data for a specific gamepad or all gamepads.

Syntax

ingamepad( gamepadIndex );

Description

Parameters

  • gamepadIndex? (number)

    Gamepad index to retrieve. If null/undefined, returns all gamepads.

Returns

  • *Many

    Gamepad object if index provided, or array of all gamepads if index is null/undefined.

Example

$.screen( "300x200" );
let x = 150;
let y = 100;
let lt = 0;
requestAnimationFrame( run );
function run( t ) {
	let gamepads = $.ingamepad();
	let factor = ( t - lt ) * 0.5;
	lt = t;
	$.cls();
	if( gamepads.length > 0 ) {
		x = Math.min( Math.max( x + gamepads[ 0 ].axes[ 0 ] * factor, 0 ), 299 );
		y = Math.min( Math.max( y + gamepads[ 0 ].axes[ 1 ] * factor, 0 ), 199 );
		if( gamepads[ 0 ].getButtonPressed( 0 ) ) {
			$.setColor( 2 );
		} else {
			$.setColor( 15 );
		}
		$.circle( Math.floor( x ), Math.floor( y ) , 9 );
		$.pset( Math.floor( x ), Math.floor( y ) );
	}
	requestAnimationFrame( run );
}

See Also

inkey

Gets the current state of a key or all pressed keys.

Syntax

inkey( key );

Description

Parameters

  • key? (string)

    Key code or key value to check. If omitted, returns all pressed keys.

Returns

  • *Many

    Key data object if key is pressed, array of all pressed keys if no key specified, or null if key not pressed.

Example

$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
	let keys = $.inkey();
	$.cls();
	$.print( "Press any key" );
	for( let key in $.inkey() ) {
		$.print( "--------------------------" );
		$.print( "key:      " + keys[ key ].key );
		$.print( "location: " + keys[ key ].location );
		$.print( "code:     " + keys[ key ].code );
	}
	requestAnimationFrame( run );
}

See Also

inmouse

Gets the current mouse state and starts tracking if needed.

Syntax

inmouse();

Description

Returns

  • MouseData

    Mouse data object with position, buttons, and action properties.

Example

$.screen( "300x200" );
requestAnimationFrame( run );
let tail = [];
let c = 7;
let pal = $.getPal();
function run() {
	$.cls();
	const mouse = $.inmouse();
	if( mouse.buttons > 0 ) {
		c = ( c + 1 ) % pal.length;
		if( c === 1 ) {
			c = 1;
		}
	}
	if( mouse.lastX !== undefined && mouse.lastY !== undefined ) {
		tail.push( [ mouse.lastX, mouse.lastY, c ] );
		if( tail.length > 50 ) {
			tail.shift();
		}
	}
	let lastPt = null;
	for( const pt of tail ) {
		if( lastPt !== null ) {
			$.setColor( pt[ 2 ] );
			$.line( lastPt[ 0 ], lastPt[ 1 ], pt[ 0 ], pt[ 1 ] );
		}
		lastPt = pt;
	}
	requestAnimationFrame( run );
}

See Also

inpress

Gets the current press state (mouse or touch) and starts tracking if needed.

Syntax

inpress();

Description

Returns

  • PressData

    Press data object (mouse or touch) with position, buttons, action, and type properties.

Example

$.screen( "300x200" );
$.setPinchZoom( false );
requestAnimationFrame( run );
let tail = [];
function run() {
	const press = $.inpress();
	$.cls();
	
	// Draw press indicator
	if( press.buttons > 0 ) {
		$.setColor( 15 );
		$.circle( press.x, press.y, 10 );
		
		// Draw trail while dragging
		if( press.lastX !== undefined && press.lastY !== undefined && press.action === "move" ) {
			tail.push( [ press.x, press.y ] );
			if( tail.length > 50 ) {
				tail.shift();
			}
			let lastPt = null;
			for( const pt of tail ) {
				if( lastPt !== null ) {
					$.setColor( 7 );
					$.line( lastPt[ 0 ], lastPt[ 1 ], pt[ 0 ], pt[ 1 ] );
				}
				lastPt = pt;
			}
		}
		
		// Show input type
		$.setColor( 2 );
		$.print( `Input: ${press.type}` );
	} else {
		$.print( "Press and drag to draw" );
		tail = [];
	}
	
	requestAnimationFrame( run );
}

See Also

input

Prompts the user for text input with a blinking cursor.

Syntax

input( prompt, fn, cursor, isNumber, isInteger, allowNegative, maxLength );

Description

Parameters

  • prompt (string)

    Prompt text to display before the input field.

  • fn? (function)

    Optional callback function called with the input value when input completes.

  • cursor? (string)

    Cursor character to display. Defaults to block character (█).

  • isNumber? (boolean)

    If true, only allows numeric input.

  • isInteger? (boolean)

    If true, only allows integer input (no decimals).

  • allowNegative? (boolean)

    If true, allows negative numbers (for numeric input).

  • maxLength? (number)

    Maximum length of the input string. If null, no limit.

Returns

  • Promise

    Promise that resolves with the input value (string or number) or null if cancelled.

Example

$.screen( "300x200" );
$.input( "Enter your name: ", async ( name ) => {
	$.print( `Hello, ${name}!` );
	const age = await $.input( {
		"prompt": "Enter age: ",
		"isNumber": true,
		"isInteger": true,
		"allowNegative": false
	} );
	$.print( `You are ${age} years old.` );
} );

See Also

intouch

Gets the current touch state and starts tracking if needed.

Syntax

intouch();

Description

Returns

  • *Array

    Array of touch data objects.

Example

$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
	const touches = $.intouch();
	for( const touch of touches ) {
		$.print( `Touch ${touch.id} at ${touch.x}, ${touch.y}` );
	}
	requestAnimationFrame( run );
}

See Also

line

Draws a line on the screen.

Syntax

line( x1, y1, x2, y2 );

Description

Parameters

  • x1 (number)

    The x coordinate of the starting point of the line.

  • y1 (number)

    The y coordinate of the starting point of the line.

  • x2 (number)

    The x coordinate of the ending point of the line.

  • y2 (number)

    The y coordinate of the ending point of the line.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setColor( 4 );
$.line( 15, 15, 285, 185 );
$.setColor( 2 );
$.line( 15, 185, 285, 15 );

See Also

loadAudio

Creates an audio pool for playing multiple instances of the same sound file.

Syntax

loadAudio( src, name, poolSize );

Description

Parameters

  • src (string)

    Audio file URL (e.g., 'sound.mp3', 'audio/beep.wav').

  • name (string)

    A name that can be used to identify the audio for later use.

  • poolSize? (number)

    Number of audio instances in the pool (default: 1).

Returns

  • string

    Audio ID for use with playAudio and stopAudio.

Example

$.screen( "300x200" );
$.loadAudio( "media/bomb.wav", "bomb", 5 );
$.ready( function () {
	$.print( "Press any key to play bomb sound." );
	$.onkey( "any", "down", () => {
		$.print( "BOOM ", true );
		$.playAudio( "bomb" );
	}, false, true );
} );

See Also

loadFont

Loads a bitmap font from an image source.

Syntax

loadFont( src, width, height, margin, charset );

Description

Parameters

  • src (*Many)

    Font image source: URL string, Image element, or Canvas element.

  • width (number)

    Character width in pixels (glyph width, excluding margin).

  • height (number)

    Character height in pixels (glyph height, excluding margin).

  • margin? (number)

    Margin around each character cell in pixels. Defaults to 0.

  • charset? (*Many)

    Character set as array of character codes or string. Defaults to 0-255 (ASCII) if not provided.

Returns

  • number

    Font ID that can be used with setFont.

Example

const fontId = $.loadFont( {
	"src": "media/gnsh.png",
	"width": 5,
	"height": 12,
	"margin": 0,
	"charset": " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]" +
			   "^_`abcdefghijklmnopqrstuvwxyz{|}~"
} );
$.ready( () => {
	$.screen( "300x200" );
	$.setFont( fontId );
	$.setBgColor( "#555" );
	$.setPosPx( 0, 85 );
	$.print( "The quick brown fox jumped over the lazy dogs! 123456789", true, true );
} );

See Also

loadImage

Loads an image by URL or from an Image/Canvas element.

Syntax

loadImage( src, name, usePalette, paletteKeys, onLoad, onError );

Description

Parameters

  • src (*Many)

    Image source: URL string, HTMLImageElement, or HTMLCanvasElement.

  • name? (string)

    Optional unique name for the image. Auto-generated if omitted.

  • usePalette? (boolean)

    If true, link image colors to the active screen palette.

  • paletteKeys? (*Array)

    Key colors used to map image colors to palette indices (required if usePalette).

  • onLoad? (function)

    Callback invoked when the image finishes loading.

  • onError? (function)

    Callback invoked if the image fails to load.

Returns

  • string

    The image name.

Example

$.screen( "300x200" );
$.loadImage( "media/player.png", "player" );
$.ready( () => {
	$.drawImage( "player", 150, 100 );
} );

See Also

loadSpritesheet

Loads a spritesheet by URL or from an Image/Canvas element.

Syntax

loadSpritesheet( src, name, width, height, margin, usePalette, paletteKeys, onLoad, onError );

Description

Parameters

  • src (*Many)

    Spritesheet source: URL string, HTMLImageElement, or HTMLCanvasElement.

  • name? (string)

    Optional unique name for the spritesheet. Auto-generated if omitted.

  • width? (number)

    Sprite width for fixed grid mode.

  • height? (number)

    Sprite height for fixed grid mode.

  • margin? (number)

    Margin between sprites in fixed grid mode (default 0).

  • usePalette? (boolean)

    If true, link image colors to the active screen palette.

  • paletteKeys? (*Array)

    Key colors used to map image colors to palette indices (required if usePalette).

  • onLoad? (function)

    Callback invoked when the spritesheet finishes loading.

  • onError? (function)

    Callback invoked if the spritesheet fails to load.

Returns

  • string

    The spritesheet name.

Example

$.screen( "150x100" );
$.setDefaultAnchor( 0.5, 0.5 );
$.loadSpritesheet( "media/cat_sprite.png", "cat", 34, 34, 1 );
let catData;
$.ready( () => {
	catData = $.getSpritesheetData( "cat" );
	requestAnimationFrame( animate );
} );

function animate( t ) {
	$.cls();
	const frame = Math.round( t / 100 ) % catData.frameCount;
	$.drawSprite( "cat", frame, 75, 50 );
	requestAnimationFrame( animate );
}

See Also

offclick

Removes a click event handler.

Syntax

offclick( fn );

Description

Parameters

  • fn? (function)

    Callback function that matches the original handler. If null, removes all click handlers.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
const handler = ( clickData ) => {
	$.setPosPx( clickData.x, clickData.y );
	$.setColor( 3 );
	$.print( "Clicked!", true );
};
$.onclick( handler );
let countDown = 5;
const interval = setInterval( () => {
	$.setColor( 7 );
	$.setPos( 0, 5 - countDown );
	$.print( `Count down to offclick: ${countDown}` );
	countDown -= 1;
	if( countDown === -1 ) {
		$.print( "Click is now disabled!" );
		clearInterval( interval );
		$.offclick( handler );
	}
}, 1000 );

See Also

offkey

Removes a key event handler.

Syntax

offkey( key, mode, fn, once, allowRepeat );

Description

Parameters

  • key (*Many)

    Key code/key value string or array of keys that matches the original handler.

  • mode? (string)

    Event mode ("up" or "down") that matches the original handler.

  • fn (function)

    Callback function that matches the original handler.

  • once? (boolean)

    Once flag that matches the original handler.

  • allowRepeat? (boolean)

    AllowRepeat flag that matches the original handler.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Press any key." );
$.print( "Press q to stop" );
$.onkey( "any", "down", keyPress );
$.onkey( "q", "down", stopPress );

// Key press function receives keyData
function keyPress( keyData ) {
	$.print( "You pressed " + keyData.key + "!" );
}

// Stop key press function receives keyData
function stopPress( keyData ) {
	$.print( "You pressed q! Stopping." );
	$.offkey( "any", "down", keyPress );
	$.offkey( "q", "down", keyPress );
}

See Also

offmouse

Removes a mouse event handler.

Syntax

offmouse( mode, fn );

Description

Parameters

  • mode (string)

    Event mode ('down', 'up', or 'move') that matches the original handler.

  • fn? (function)

    Callback function that matches the original handler. If null, removes all handlers for this mode.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Move mouse to paint screen, click to stop." );
$.onmouse( "move", mouseMove );
$.onmouse( "up", mouseStop, true );

// Mouse move function receives mouseData and optional customData
function mouseMove( mouseData, customData ) {
	$.setPosPx( mouseData.x, mouseData.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 8 );
	$.print( "+", true );
}

// Mouse stop function receives mouseData and optional customData
function mouseStop( mouseData, customData ) {
	$.setColor( 14 );
	var pos = $.getPos();
	$.setPos( pos.col - 4, pos.row );
	$.print( "Stopped!", true );
	$.offmouse( "move", mouseMove );
}

See Also

offpress

Removes a press event handler.

Syntax

offpress( mode, fn );

Description

Parameters

  • mode (string)

    Event mode ('down', 'up', or 'move') that matches the original handler.

  • fn? (function)

    Callback function that matches the original handler. If null, removes all handlers for this mode.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Move mouse or touch to paint screen, click/touch up to stop." );
$.onpress( "move", pressMove );
$.onpress( "up", pressStop, true );

// Press move function receives pressData and optional customData
function pressMove( pressData, customData ) {
	$.setPosPx( pressData.x, pressData.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 8 );
	$.print( "+", true );
}

// Press stop function receives pressData and optional customData
function pressStop( pressData, customData ) {
	$.setColor( 14 );
	var pos = $.getPos();
	$.setPos( pos.col - 4, pos.row );
	$.print( "Stopped!", true );
	$.offpress( "move", pressMove );
}

See Also

offtouch

Removes a touch event handler.

Syntax

offtouch( mode, fn );

Description

Parameters

  • mode (string)

    Event mode ('start', 'end', or 'move') that matches the original handler.

  • fn? (function)

    Callback function that matches the original handler. If null, removes all handlers for this mode.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Touch and drag to paint screen, touch up to stop." );
$.ontouch( "move", touchMove );
$.ontouch( "end", touchStop, true );

// Touch move function receives touchDataArray and optional customData
function touchMove( touches, customData ) {
	$.setPosPx( touches[ 0 ].x, touches[ 0 ].y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 8 );
	$.print( "+", true );
}

// Touch stop function receives touchDataArray and optional customData
function touchStop( touches, customData ) {
	$.setColor( 14 );
	var pos = $.getPos();
	$.setPos( pos.col - 4, pos.row );
	$.print( "Stopped!", true );
	$.offtouch( "move", touchMove );
}

See Also

onclick

Registers a callback function for click events (mouse or touch).

Syntax

onclick( fn, once, hitBox, customData );

Description

Parameters

  • fn (function)

    Callback function that receives (clickData, customData) when a click occurs.

  • once? (boolean)

    If true, the handler is removed after being called once.

  • hitBox? (HitBox)

    Optional hit box object with x, y, width, height properties. Click only fires if press is within this area. Defaults to full screen.

  • customData? (any)

    Optional custom data passed to the callback function.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.onclick( ( clickData ) => {
	$.setPosPx( clickData.x, clickData.y );
	$.print( `Clicked`, true );
} );

See Also

onGamepadConnected

Registers a callback function for when a gamepad is connected.

Syntax

onGamepadConnected( fn );

Description

Parameters

  • fn (function)

    Callback function that receives (gamepad) when a gamepad connects.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Connect gamepad and press a button or move an axis to connect" );
$.onGamepadConnected( ( gamepad ) => {
	$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
} );

See Also

onGamepadDisconnected

Registers a callback function for when a gamepad is disconnected.

Syntax

onGamepadDisconnected( fn );

Description

Parameters

  • fn (function)

    Callback function that receives (gamepad) when a gamepad disconnects.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Connect gamepad and press a button or move an axis to connect" );
$.onGamepadConnected( ( gamepad ) => {
	$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
} );
$.onGamepadDisconnected( ( gamepad ) => {
	$.print( `Gamepad ${gamepad.index} disconnected: ${gamepad.id}` );
} );

See Also

onkey

Registers a callback function for key events.

Syntax

onkey( key, mode, fn, once, allowRepeat );

Description

Parameters

  • key (*Many)

    Key code/key value string, array of keys for combinations, or "any" for any key.

  • mode (string)

    Event mode: "up" for key release, "down" for key press.

  • fn (function)

    Callback function that receives key data object(s) when the event occurs.

  • once? (boolean)

    If true, the handler is removed after being called once.

  • allowRepeat? (boolean)

    If true, allows the handler to fire on key repeat (when key is held down).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.onkey( "Enter", "down", ( keyData ) => {
	$.print( "Enter pressed!" );
} );

// Key combination
$.onkey( [ "Control", "c" ], "down", ( keys ) => {
	$.print( "Ctrl+C pressed!" );
} );

// One-time handler
$.onkey( "Space", "down", () => {
	$.print( "Space pressed once!" );
}, true );

// Listen for any key
$.onkey( "any", "down", ( keyData ) => {
	$.print( `Key ${keyData.key} pressed` );
} );

See Also

onmouse

Registers a callback function for mouse events.

Syntax

onmouse( mode, fn, once, hitBox, customData );

Description

Parameters

  • mode (string)

    Event mode: 'down', 'up', or 'move'.

  • fn (function)

    Callback function that receives (mouseData, customData) when the event occurs.

  • once? (boolean)

    If true, the handler is removed after being called once.

  • hitBox? (HitBox)

    Optional hit box object with x, y, width, height properties. Callback only fires if mouse is within this area.

  • customData? (any)

    Optional custom data passed to the callback function.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.onmouse( "down", ( mouseData ) => {
	$.setPosPx( mouseData.x, mouseData.y );
	$.print( `(${mouseData.x}, ${mouseData.y})` );
} );

// With hit box
const hitBox = { "x": 10, "y": 10, "width": 100, "height": 50 };
$.setColor( 2 );
$.rect( hitBox );
$.setColor( 7 );
$.onmouse( "move", ( mouseData ) => {
	$.setColor( 3 );
	$.pset( mouseData.x, mouseData.y );
	$.setColor( 7 );
}, false, hitBox );

// One-time handler
$.onmouse( "up", () => {
	$.setPos( 0, 12 )
	$.print( "Mouse released once", true, true );
}, true );

See Also

onpress

Registers a callback function for press events (mouse or touch).

Syntax

onpress( mode, fn, once, hitBox, customData );

Description

Parameters

  • mode (string)

    Event mode: 'down', 'up', or 'move'.

  • fn (function)

    Callback function that receives (pressData, customData) when the event occurs.

  • once? (boolean)

    If true, the handler is removed after being called once.

  • hitBox? (HitBox)

    Optional hit box object with x, y, width, height properties. Callback only fires if press is within this area.

  • customData? (any)

    Optional custom data passed to the callback function.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.onpress( "down", ( pressData ) => {
	$.setPosPx( pressData.x, pressData.y );
	$.print( `(${pressData.x}, ${pressData.y})` );
} );

// With hit box
const hitBox = { "x": 10, "y": 10, "width": 100, "height": 50 };
$.setColor( 2 );
$.rect( hitBox );
$.setColor( 7 );
$.onpress( "move", ( pressData ) => {
	$.setColor( 3 );
	$.pset( pressData.x, pressData.y );
	$.setColor( 7 );
}, false, hitBox );

// One-time handler
$.onpress( "up", () => {
	$.setPos( 0, 12 )
	$.print( "press released once", true, true );
}, true );

See Also

ontouch

Registers a callback function for touch events.

Syntax

ontouch( mode, fn, once, hitBox, customData );

Description

Parameters

  • mode (string)

    Event mode: 'start', 'end', or 'move'.

  • fn (function)

    Callback function that receives (touchDataArray, customData) when the event occurs.

  • once? (boolean)

    If true, the handler is removed after being called once.

  • hitBox? (HitBox)

    Optional hit box object with x, y, width, height properties. Callback only fires if touches are within this area.

  • customData? (any)

    Optional custom data passed to the callback function.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
let msg = "";
$.ontouch( "start", ( touches ) => {
	msg = `Touch started: ${touches.length} finger(s)`;
	$.setPos( 0, 0 );
	$.print( msg );
} );

$.ontouch( "move", ( touches ) => {
	$.cls();
	$.setPos( 0, 0 );
	$.print( msg );
	const letters = "ABCDEFGHIJ";
	for( let i = 0; i < touches.length; i += 1 ) {
		$.setPosPx( touches[ i ].x, touches[ i ].y );
		$.print( letters[ i ] );
	}
} );

See Also

paint

Flood fills an area with a color, with optional tolerance or boundary color.

Syntax

paint( x, y, fillColor, tolerance, boundaryColor );

Description

Parameters

  • x (number)

    X (horizontal) coordinate to start filling.

  • y (number)

    Y (vertical) coordinate to start filling.

  • fillColor (any)

    Fill color. Palette index or color value (string, array, object, number).

  • tolerance? (number)

    Color matching tolerance [0.0-1.0]. 0 = exact match; 1 = any color.

  • boundaryColor? (any)

    Optional boundary color (palette index or color value). Enables boundary fill mode.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );

// Draw some rects and lines to demo paint routine
$.rect( 20, 20, 100, 60 );
$.setColor( "#111111" );
$.line( 30, 30, 50, 50 );
$.setColor( "#151515" );
$.line( 35, 30, 55, 50 );
$.setColor( "#FFFFFF" );
$.line( 45, 30, 65, 50 );
$.setColor( "red" );
$.rect( 150, 50, 120, 80 );
$.setColor( "#111111" );
$.line( 170, 80, 180, 90 );
$.setColor( "#151515" );
$.line( 190, 80, 200, 90 );
$.setColor( "#FFFFFF" );
$.line( 210, 80, 220, 90 );

// Tolerance fill (similar colors to the starting pixel)
// Should paint over the two dark gray lines but not the white line
$.paint( 25, 25, "#333300", 0.25 );

// Boundary fill (fill until reaching boundary color)
// Should paint over everything expect the boundary color which is red
$.paint( 160, 60, "#0080FF", 0.2, "red" );

See Also

play

Plays music using BASIC-style notation (inspired by QBasic PLAY command).

Syntax

play( playString );

Description

Parameters

  • playString (string)

    Music notation string with notes and commands.

Returns

  • number

    Sound ID for use with stopPlay.

Example

$.screen( "300x200" );
const tracks = [
	"T120 O3 L4 GAB>C",
	"T120 O3 L4 GAB>C,C",
	"WS T120 O3 L4 GAB>C",
	"[[0,1,0,-1],[0,0,0,0]] T120 O3 L4 GAB>C",
];
$.print( "Press any key to play music" );
$.onkey( "any", "down", () => {
	let t = 0;
	for( const track of tracks ) {
		setTimeout( () => {
			$.print( `Play: ${track}` );
			$.play( track );
		}, t );
		t += 2000;
	}
} );

See Also

playAudio

Plays audio from an audio pool.

Syntax

playAudio( audioId, volume, startTime, duration );

Description

Parameters

  • audioId (string)

    Audio pool ID returned from loadAudio.

  • volume? (number)

    Volume (0-1, default: 1).

  • startTime? (number)

    Start time in seconds (default: 0).

  • duration? (number)

    Play duration in seconds (default: 0 = play full audio).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
let bombAudio = $.loadAudio( "media/bomb.wav", null, 5 );
$.ready( function () {
	$.print( "Press any key to play bomb sound." );
	$.onkey( "any", "down", () => {
		$.print( "BOOM ", true );
		$.playAudio( bombAudio );
	}, false, true );
} );

See Also

popView

Pops the current child view and restores the parent.

Syntax

popView();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setColor( 15 );
$.pushView( 20, 20, 100, 80 );
$.paint( 0, 0, 1 );
$.pushView( 8, 8, 80, 60 );
$.paint( 0, 0, 2 );
$.print( "child: This content should wrap here" );
$.popView();
$.print( "parent" );
$.popView();
$.print( "grandparent" );

See Also

print

Prints text to the screen using the current font and advances the cursor.

Syntax

print( msg, isInline, isCentered );

Description

Parameters

  • msg? (string)

    Text message to print. If omitted, prints an empty line.

  • isInline? (boolean)

    If true, cursor stays on the same line after printing instead of advancing to next line.

  • isCentered? (boolean)

    If true, centers the text horizontally on the screen.

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setFont( 1 );
$.print( "Welcome to Pi.js" );
$.print();
$.print( "Line 1" );
$.print( "Inline text", true );
$.print( " more inline", true );
$.print();
$.print( "Centered", false, true );

See Also

pset

Sets a pixel on the screen to the current foreground color.

Syntax

pset( x, y );

Description

Parameters

  • x (number)

    The x coordinate of the pixel to set.

  • y (number)

    The y coordinate of the pixel to set.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setColor( 2 );
$.pset( 148, 101 );
$.pset( 149, 100 );
$.pset( 150, 101 );
$.pset( 151, 100 );
$.pset( 152, 101 );

See Also

pushView

Pushes a child view relative to the current view.

Syntax

pushView( x, y, width, height );

Description

Parameters

  • x (number)

    Left edge of the child view in current local coordinates.

  • y (number)

    Top edge of the child view in current local coordinates.

  • width (number)

    Requested local width in pixels. Must be 0 or greater.

  • height (number)

    Requested local height in pixels. Must be 0 or greater.

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setColor( 15 );
$.print( "grandparent" );
$.pushView( 20, 20, 100, 80 );
$.paint( 0, 0, 1 );
$.print( "parent" );
$.pushView( 8, 8, 80, 60 );
$.paint( 0, 0, 2 );
$.print( "child: This content should wrap here" );

See Also

put

Writes a 2D array of palette indices to the screen starting at (x, y).

Syntax

put( data, x, y, include0 );

Description

Parameters

  • data (*Array)

    2D array [height][width] of palette indices (0..pal.length-1).

  • x (number)

    X (horizontal) destination coordinate.

  • y (number)

    Y (vertical) destination coordinate.

  • include0? (boolean)

    If true, draw index 0 (transparent) pixels; otherwise skip them.

Returns

  • void

    This function does not return a value.

Example

var data = [
	[  1,  2,  3,  4,  5,  6 ],
	[  7,  8,  9, 10, 11, 12 ],
	[ 13, 14, 15, 16, 17, 18 ]
]
$.screen( "30x20" );
$.put( data, 1, 1 );

See Also

ready

Waits for document readiness and all pending resources.

Syntax

ready( callback );

Description

Parameters

  • callback? (function)

    Optional callback to run when ready completes.

Returns

  • Promise

    Resolves when the document and all pending resources are ready.

Example

$.screen( "128x64" );
$.loadSpritesheet( "media/tiles.png", "tiles", 16, 16, 0 );

// Wait for spritesheet to load using callback
$.ready( async function() {
	for( let y = 0; y < 64; y += 16 ) {
		for( let x = 0; x < 128; x += 16 ) {
			$.drawSprite( "tiles", 0, x, y );
		}
	}
	$.loadImage( { "src": "media/player.png", "name": "player" } );

	// Wait for image to load using await
	await $.ready();
	$.drawImage( "player", 58, 24 );
} );

See Also

rect

Draws a rectangle on the screen.

Syntax

rect( x, y, width, height, fillColor );

Description

Parameters

  • x (number)

    The x coordinate of the upper left corner of the rectangle.

  • y (number)

    The y coordinate of the upper left corner of the rectangle.

  • width (number)

    The width of the rectangle.

  • height (number)

    The height of the rectangle.

  • fillColor? (any)

    The fill color for the rectangle. Can be a palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setColor( 5 );
$.rect( 15, 15, 150, 100 );
$.rect( 25, 25, 150, 100, 6 );
$.rect( 35, 35, 150, 100, 2 );

See Also

registerPlugin

Registers a plugin to extend Pi.js with custom commands and features.

Syntax

registerPlugin( name, init, version, description, dependencies );

Description

Parameters

  • name (string)

    Unique plugin name.

  • init (function)

    Initialization function that receives pluginApi.

  • version? (string)

    Optional plugin version.

  • description? (string)

    Optional plugin description.

  • dependencies? (*Array)

    Optional list of dependency plugin names.

Returns

  • void

    This function does not return a value.

Example

$.registerPlugin( {
	"name": "octogon",
	"version": "1.0.0",
	"description": "Poly plugin",
	"dependencies": [],
	"init": ( pluginApi ) => {
		pluginApi.addCommand( "poly", ( screenData, options ) => {
			const x = options.x ?? 0;
			const y = options.y ?? 0;
			const radius = options.radius ?? 1;
			const sides = options.sides ?? 1;
			let angle = 0
			const fillColor = options.fillColor;
			let da = ( Math.PI * 2 ) / sides;
			let x2 = null;
			let y2 = null;
			for( let i = 0; i < sides + 1; i += 1 ) {
				let x1 = x + Math.cos( angle ) * radius;
				let y1 = y + Math.sin( angle ) * radius;
				if( x2 !== null ) {
					screenData.api.line( x1, y1, x2, y2 );
				}
				x2 = x1;
				y2 = y1;
				angle += da;
			}
			if( fillColor !== null ) {
				screenData.api.paint( x, y, fillColor );
			}
		}, true, [ "x", "y", "radius", "sides", "fillColor" ] );
	}
} );
$.screen( "300x200" );
$.setColor( 15 );
$.poly( 150 , 100, 15, 8, "red" );

See Also

removeActionKeys

Removes keys from the action keys set.

Syntax

removeActionKeys( keys );

Description

Parameters

  • keys (*Array)

    Array of key codes or key values to remove from action keys.

Returns

  • void

    This function does not return a value.

Example

$.screen( "200x200" );
$.setActionKeys( [ "Control", "KeyS"] );
let actionKeysRemoved = false;
setTimeout( () => {
	$.removeActionKeys( [ "Control", "KeyS" ] );
	actionKeysRemoved = true;
}, 5000 );
setInterval( function () {
	let keys = $.inkey();
	$.cls();
	$.print( "Press Ctrl+S." );
	if( actionKeysRemoved ) {
		$.print( "Action Keys Removed" );
	}
	let key = $.inkey( "Control" );
	if( key ) {
		$.print( "Control key is pressed." );
	} else {
		$.print( "Control key is not pressed." );
	}
	for( key in keys ) {
		$.print( "--------------------------" );
		$.print( "key:      " + keys[ key ].key );
		$.print( "location: " + keys[ key ].location );
		$.print( "code:     " + keys[ key ].code );
	}
}, 60 );

See Also

removeAllScreens

Removes all screens from memory and the DOM.

Syntax

removeAllScreens();

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setColor( 5 );
$.rect( 25, 25, 150, 100, 2 );
$.removeAllScreens();

removeAudio

Removes an audio pool and frees its resources.

Syntax

removeAudio( audioId );

Description

Parameters

  • audioId (string)

    Audio ID returned from loadAudio.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
let bombAudio = $.loadAudio( "media/bomb.wav", null, 5 );
$.ready( function () {
	$.print( "Press any key to try to play bomb sound." );
	$.removeAudio( bombAudio );
	$.onkey( "any", "down", () => {
		try {
			$.playAudio( bombAudio );
		} catch (e) {
			$.print( "SILENCE ", true );
		}
	}, false, true );
} );

See Also

removeImage

Removes a previously loaded image by name.

Syntax

removeImage( name );

Description

Parameters

  • name (string)

    Image name to remove.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
const playerA = document.createElement( "canvas" );
playerA.width = 32;
playerA.height = 32;
const context = playerA.getContext( "2d" );
context.fillStyle = "red";
context.font = "16pt Arial Bold";
context.fillText( "A", 0, 16 );
$.loadImage( playerA, "player" );
$.drawImage( "player", 5, 5 );
$.removeImage( "player" );
try {
	$.drawImage( "player", 5, 21 );
} catch( error ) {
	$.print( error.code );
}

See Also

removeScreen

Removes a screen and cleans up all associated resources.

Syntax

removeScreen( screen );

Description

Parameters

  • screen? (*Many)

    Screen ID (number) or screen API object to remove.

Returns

  • void

    This function does not return a value.

Example

const screen1 = $.screen( "320x200" );
$.removeScreen( screen1 );

// Or call as method on screen object
const screen2 = $.screen( "640x480" );
screen2.removeScreen();

See Also

removeShader

Removes a custom shader and releases its cached GPU programs.

Syntax

removeShader( shaderHandle );

Description

Parameters

  • shaderHandle (number)

    Shader handle returned by createShader.

Returns

  • void

    This function does not return a value.

Example

const invert = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4(1.0 - color.rgb, color.a);
}` );

$.screen( "320x200" );
$.rect( 5, 5, 16, 16, "red" );
$.applyShader( invert );
$.rect( 32, 32, 16, 16, "red" );
$.removeShader( invert );
try {
	$.applyShader( invert );
} catch( ex ) {
	$.setPos( 0, 6 );
	$.print( ex.message );
}

See Also

resetView

Clears the view stack and resets to full screen.

Syntax

resetView();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.pushView( 20, 10, 120, 80 );
$.pushView( 8, 8, 40, 30 );
$.print( "nested" );
$.resetView();
$.print( "full screen" );

See Also

screen

Creates a new screen (canvas) with specified dimensions and aspect ratio.

Syntax

screen( aspect, container, isOffscreen, resizeCallback, parent );

Description

Parameters

  • aspect (string)

    Aspect ratio string in format (width)(x|e|m)(height), e.g., '300x200', '100e00', '300m200'.

  • container? (*Many)

    DOM element or element ID string to use as container. Defaults to document.body.

  • isOffscreen? (boolean)

    If true, creates an offscreen canvas that is not displayed. Requires exact pixel dimensions.

  • resizeCallback? (function)

    Callback function called when screen is resized. Receives (screenApi, fromSize, toSize).

  • parent? (*Many)

    Existing screen ID or screen API object whose WebGL context the offscreen screen uses. Only valid when isOffscreen is true. Enables fast drawImage calls directly from the offscreen framebuffer and does not establish lifecycle ownership.

Returns

  • Screen

    Screen API object with all graphics command and screen=true and id property.

Example

const parent = $.screen( { "aspect": "320x200" } );
const offscreen = $.screen( {
	"aspect": "160x100",
	"isOffscreen": true,
	"parent": parent
} );

$.cls( 1 );
$.circle( 80, 50, 32, "red" );

$.setScreen( parent );
$.drawImage( offscreen, 80, 50 );

See Also

screenToView

Converts a screen point to local view coordinates.

Syntax

screenToView( x, y );

Description

Parameters

  • x (number)

    Screen / FBO x coordinate.

  • y (number)

    Screen / FBO y coordinate.

Returns

  • PositionPx

    Local view position { x, y }.

Example

$.screen( "320x200" );
$.pushView( 40, 20, 100, 80 );
const local = $.screenToView( 45, 25 );
$.print( local.x + "," + local.y );

See Also

set

Applies multiple settings in a single call using an options object.

Syntax

set( options );

Description

Parameters

  • options (Options)

    Object whose keys map to available settings (e.g., { "screen": "300x200", "color": 2 }).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.set( { "color": 10, "font": 2, "pos": { "col": 5, "row": 5 }, "bgColor": "#267" } );
$.print( "Settings have been applied" );

See Also

setActionKeys

Sets keys that should prevent default browser behavior.

Syntax

setActionKeys( keys );

Description

Parameters

  • keys (*Array)

    Array of key codes or key values to add as action keys.

Returns

  • void

    This function does not return a value.

Example

$.screen( "200x200" );
$.setActionKeys( [ "Control", "KeyS"] );
setInterval( function () {
	let keys = $.inkey();
	$.cls();
	$.print( "Press Ctrl+S." );
	let key = $.inkey( "Control" );
	if( key ) {
		$.print( "Control key is pressed." );
	} else {
		$.print( "Control key is not pressed." );
	}
	for( key in keys ) {
		$.print( "--------------------------" );
		$.print( "key:      " + keys[ key ].key );
		$.print( "location: " + keys[ key ].location );
		$.print( "code:     " + keys[ key ].code );
	}
}, 60 );

See Also

setBlend

Sets the current blend mode used for rendering.

Syntax

setBlend( blend );

Description

Parameters

  • blend (string)

    Blend mode to use. One of: "replace", "alpha".

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setBlend( "alpha" );
$.rect( 20, 20, 80, 80, "#AA0000FF" );
$.rect( 40, 40, 80, 80, "#00AA0088" );

See Also

setChar

Sets a custom character bitmap in the current font.

Syntax

setChar( charCode, data );

Description

Parameters

  • charCode (*Many)

    Character code (number) or single-character string to modify.

  • data (*Many)

    Character bitmap as 2D array [[row...], ...] where 1=on, 0=off, or hex-encoded string.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setFont( 2 );
$.setChar( 97, "1092ba547cc6fe92" );
$.setChar( 98, "423c2418187e1818" );
$.setChar( 99, "7cd67cfec6aafe00" );
$.setChar( 100, "00183c667e5a42c3" );
$.setChar( 101, "008199FFDBFFBD18" );

$.print( " abcde f" );

See Also

setColor

Sets the current foreground color used for drawing.

Syntax

setColor( color );

Description

Parameters

  • color (any)

    Palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.screen( "360x300" );
let colors = $.getPal();
let x = 0;
let y = 0;
let size = 20;
for( let i = 0; i < colors.length; i += 1 ) {
	$.setColor( i );
	$.rect( x, y, size, size );
	$.setPosPx( x + 1, y + 4 );
	$.print( i, true );
	x += size;
	if( x >= $.width() ) {
		x = 0;
		y += size;
	}
}

See Also

setContainerBgColor

Sets the background color of the screen's container element.

Syntax

setContainerBgColor( color );

Description

Parameters

  • color (any)

    Palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setContainerBgColor( "#202040" );

See Also

setDefaultAnchor

Sets the default anchor point for images when drawing on the current screen.

Syntax

setDefaultAnchor( x, y );

Description

Parameters

  • x (number)

    Anchor X in range [0.0-1.0].

  • y (number)

    Anchor Y in range [0.0-1.0].

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.loadImage( "media/spaceship_0.png", "ship" );

// Set the anchor point to the center of the ship so that the image will rotate correctly
$.setDefaultAnchor( 0.5, 0.5 );
$.ready( () => {
	run();
} );
let angle = 0;
function run() {
	$.cls();
	$.drawImage( { "image": "ship", "x": 150, "y": 100, "angle": angle } );
	angle += 1;
	requestAnimationFrame( run );
}

See Also

setDefaultColor

Sets the default foreground color used by new screens.

Syntax

setDefaultColor( color );

Description

Parameters

  • color (any)

    Palette index or color value (string, array, object, number).

Returns

  • void

    This function does not return a value.

Example

$.setDefaultColor( 9 );
$.screen( "300x200" );
$.rect( 100, 50, 100, 100 );

See Also

setDefaultFont

Sets the default font for new screens.

Syntax

setDefaultFont( fontId );

Description

Parameters

  • fontId (number)

    Font ID from loadFont to use as default for new screens.

Returns

  • void

    This function does not return a value.

Example

const fontId = $.loadFont( {
	"src": "media/gnsh.png",
	"width": 5,
	"height": 12,
	"margin": 0,
	"charset": " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]" +
			   "^_`abcdefghijklmnopqrstuvwxyz{|}~"
} );
$.ready( () => {
	$.setDefaultFont( fontId );
	$.screen( "300x200" );
	$.setBgColor( "#555" );
	$.setPosPx( 0, 85 );
	$.print( "The quick brown fox jumped over the lazy dogs! 123456789", true, true );
} );

See Also

setDefaultPal

Sets the default color palette for newly created screens.

Syntax

setDefaultPal( pal );

Description

Parameters

  • pal (*Array)

    Array of color values (names, hex, RGBA, or palette indices).

Returns

  • void

    This function does not return a value.

Example

const pal = [ "#0000FF", "red", [ 0, 255, 0 ], [ 255, 255, 0, 255 ] ];
$.setDefaultPal( pal );
$.screen( "300x200" );
const newPal = $.getPal( true );
let x = 90;
let y = 5;
for( const color of newPal ) {
	$.setColor( "#AAA" );
	$.print( `Color Index: ${$.getPalIndex( color )}` );
	$.setColor( color );
	$.print( `[${color.array.join( ", " )}]` );
	$.print();
	$.rect( x, y, 100, 100 );
	x += 25;
	y += 15;
}

See Also

setDisplayShader

Sets or clears the custom display shader for final presentation.

Syntax

setDisplayShader( shaderHandle, uniforms );

Description

Parameters

  • shaderHandle (number | null)

    Shader handle from createShader, or null to restore the default display path.

  • uniforms? (ShaderUniforms)

    Optional initial display uniform overrides. Replaces prior overrides.

Returns

  • void

    This function does not return a value.

Example

const invert = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4(1.0 - color.rgb, color.a);
}` );

// Screen 0 inverts colors
$.screen( "320x200" );
$.setColor( 4 );
$.circle( 160, 100, 40, 4 );
$.setDisplayShader( invert );

// Screen 1 should not invert colors
$.screen( "320x200" );
$.setBgColor( 0 );
$.setColor( 4 );
$.circle( 180, 120, 40, 4 );
$.setDisplayShader( invert );
$.setDisplayShader( null );

See Also

setDisplayShaderUniforms

Merges persistent display-shader uniform overrides and re-presents.

Syntax

setDisplayShaderUniforms( uniforms );

Description

Parameters

  • uniforms (ShaderUniforms)

    Uniform values to merge into the active display-shader overrides.

Returns

  • void

    This function does not return a value.

Example

const tint = $.createShader( `#version 300 es
precision mediump float;
in vec2 v_texCoord;
uniform sampler2D u_texture;
uniform float u_gain;
out vec4 fragColor;
void main() {
	vec4 color = texture(u_texture, v_texCoord);
	fragColor = vec4(color.rgb * u_gain, color.a);
}` );

$.screen( "320x200" );
$.setColor( 14 );
$.circle( 160, 100, 40, 4 );
$.setDisplayShader( tint, { "u_gain": 1 } );
$.setDisplayShaderUniforms( { "u_gain": 0.5 } );

See Also

setEnableContextMenu

Enables or disables the right-click context menu.

Syntax

setEnableContextMenu( isEnabled );

Description

Parameters

  • isEnabled (boolean)

    If true, enables the context menu. If false, disables it (default).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Try right click to see if context menu appears." );
$.setEnableContextMenu( false );

See Also

setGamepadSensitivity

Sets the dead zone sensitivity for gamepad analog sticks.

Syntax

setGamepadSensitivity( sensitivity );

Description

Parameters

  • sensitivity (number)

    Sensitivity threshold between 0 and 1 (0 = no dead zone, 1 = maximum dead zone).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setGamepadSensitivity( 0.2 );
run();
function run() {
	const gamepad = $.ingamepad( 0 );
	if( gamepad ) {
		const vAxis = gamepad.getAxis( 0 );
		$.cls();
		$.circle( Math.floor( 300 * ( vAxis / 2 ) ) + 150, 100, 8 );
	}
	requestAnimationFrame( run );
}

See Also

setNoise

Configures color noise ranges and optional seed for blending.

Syntax

setNoise( noise, seed );

Description

Parameters

  • noise? (*Many)

    Noise configuration (number, 1D array, or 2D min/max arrays).

  • seed? (number)

    Optional noise seed used for deterministic noise.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );

// Single value (symmetric range on all channels)
$.setNoise( 24, 0 );
$.rect( 25, 25, 50, 50, 2 );

// Per-channel symmetric ranges
$.setNoise( [ 16, 8, 0, 0 ], 0 );
$.rect( 100, 25, 50, 50, 2 );

// Explicit per-channel min/max ranges
$.setNoise( [ [ 100, 4, 0, 0 ], [ 255, 12, 0, 0 ] ], 0 );
$.rect( 175, 25, 50, 50, 2 );

See Also

setPal

Replaces the current palette with a new set of colors.

Syntax

setPal( pal );

Description

Parameters

  • pal (*Array)

    Array of color values (names, hex, RGBA, or palette indices).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setPal( [ "white", "red", "green", "blue" ] );
$.setColor( 1 );
$.print( "white" );
$.setColor( 2 );
$.print( "red" );
$.setColor( 3 );
$.print( "green" );
$.setColor( 4 );
$.print( "blue" );

See Also

setPalColors

Updates one or more palette colors at specific indices.

Syntax

setPalColors( indices, colors );

Description

Parameters

  • indices (*Array)

    Array of palette indices to change.

  • colors (*Array)

    Array of color values corresponding to indices.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.setPalColors( [ 1, 2, 3 ], [ "white", "#FF00FF", [ 0, 255, 128 ] ] );
$.setColor( 1 );
$.print( "white" );
$.setColor( 2 );
$.print( "#FF00FF" );
$.setColor( 3 );
$.print( [ 0, 255, 128 ] );

See Also

setPinchZoom

Enables or disables browser pinch zoom gestures.

Syntax

setPinchZoom( isEnabled );

Description

Parameters

  • isEnabled (boolean)

    If true, enables pinch zoom. If false, disables it.

Returns

  • void

    This function does not return a value.

Example

$.setPinchZoom( false ); // Disable pinch zoom for game controls
$.setPinchZoom( true ); // Re-enable pinch zoom

See Also

setPos

Sets the print cursor position using column and row coordinates.

Syntax

setPos( col, row );

Description

Parameters

  • col? (number)

    Column position (0-indexed).

  • row? (number)

    Row position (0-indexed).

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setFont( 1 );
$.setPos( 5, 10 );
$.print( "X" );
$.setPos( { "col": 10, "row": 15 } );
$.print( "Y" );

See Also

setPosPx

Sets the print cursor position using pixel coordinates.

Syntax

setPosPx( x, y );

Description

Parameters

  • x? (number)

    X position in pixels.

  • y? (number)

    Y position in pixels.

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setFont( 1 );
$.setPosPx( 50, 100 );
$.print( "At pixel 50, 100" );
$.setPosPx( { "x": 100, "y": 150 } );
$.print( "At pixel 100, 150" );

See Also

setPrintSize

Sets the scale factor for printed text.

Syntax

setPrintSize( scaleWidth, scaleHeight, padX, padY );

Description

Parameters

  • scaleWidth? (number)

    Horizontal scale factor (must be number >= 0).

  • scaleHeight? (number)

    Vertical scale factor (must be number >= 0).

  • padX? (number)

    Extra horizontal padding between characters in pixels. Defaults to 0.

  • padY? (number)

    Extra vertical padding between lines in pixels. Defaults to 0.

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setFont( 1 );
$.print( "Normal size" );
$.setPrintSize( 2, 2 );
$.print( "Double size" );
$.setPrintSize( { "scaleWidth": 1, "scaleHeight": 2.5 } );
$.print( "Ultra thin tall font" );

See Also

setScreen

Sets the active screen for graphics commands.

Syntax

setScreen( screen );

Description

Parameters

  • screen (*Many)

    Screen ID (number) or screen API object to set as active.

Returns

  • void

    This function does not return a value.

Example

const screen0 = $.screen( "320x200" );
const screen1 = $.screen( "320x200" );
screen1.setBgColor( "rgba(0,0,0,0)" );
$.setScreen( screen0 );
$.line( 0, 0, 320, 200 );
$.setScreen( { "screen": 1 } );
$.line( 0, 0, 320, 200 );

See Also

setVolume

Sets the global volume for all sounds and audio pools.

Syntax

setVolume( volume );

Description

Parameters

  • volume (number)

    Volume (0-1, default: 0.75).

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Press any key to hear some music" );
$.onkey( "any", "down", () => {
	$.setVolume( 0.15 );
	$.play( "Q1o3L8ED+ED+Eo2Bo3DCL2o2A" );
	setTimeout( () => {
		$.setVolume( 1 );
	}, 730 );
} );

See Also

setWordBreak

Enables or disables word breaking for text wrapping.

Syntax

setWordBreak( isEnabled );

Description

Parameters

  • isEnabled (boolean)

    If true, enable word breaking at spaces. If false, break at any character.

Returns

  • void

    This function does not return a value.

Example

$.screen( "320x200" );
$.setFont( 1 );
$.setWordBreak( true );
$.print( "This is a very long line of text that will wrap at word boundaries" );
$.setWordBreak( false );
$.print( "This text will break anywhere when it reaches the edge" );

See Also

sound

Plays a sound by frequency using Web Audio API.

Syntax

sound( frequency, duration, volume, oType, delay, attack, decay );

Description

Parameters

  • frequency? (number)

    Frequency in Hz (default: 440).

  • duration? (number)

    Duration in seconds (default: 1).

  • volume? (number)

    Volume 0-1 (default: 1).

  • oType? (*Many)

    Oscillator type: 'triangle', 'sine', 'square', 'sawtooth', or custom wavetable array [[realArray], [imagArray]] (default: 'triangle').

  • delay? (number)

    Delay before playing in seconds (default: 0).

  • attack? (number)

    Attack time in seconds (default: 0).

  • decay? (number)

    Decay time in seconds (default: 0.1).

Returns

  • string

    Sound ID for use with stopSound.

Example

const data = [
  392, 8, "My ", 659, 8, "Bon-", 587, 8, "nie ", 523, 8, "lies ", 587, 8,
  "o-", 523, 8, "ver ", 440, 8, "the ", 392, 8, "o-", 330, 32, "cean\n",
  392, 8, "My ", 659, 8, "Bon-", 587, 8, "nie ", 523, 8, "lies ", 523, 8,
  "o-", 494, 8, "ver ", 523, 8, "the ", 587, 40, "sea\n", 392, 8, "My ",
  659, 8, "Bon-", 587, 8, "nie", 523, 8, " lies ", 587, 8, "o-", 523, 8,
  "ver ", 440, 8, "the ", 392, 8, "o-", 330, 32, "cean\n", 392, 8, "Oh ",
  440, 8, "bring ", 587, 8, "back ", 523, 8, "my ", 494, 8, "Bon-", 440,
  8, "nie ", 494, 8, "to ", 523, 32, "me"
];
const printTimeouts = [];
const volume = 0.15;

let totalDuration = 0;
let attackRate = 0.01;
let decayRate = 0.1;
let sustainRate = 0.89;
$.screen( "300x200" );
$.print( "Press any key to hear the song" );
$.onkey( "any", "down", () => {
	for( let i = 0; i < data.length; i += 3 ) {
		const freq = data[ i ];
		const duration = data[ i + 1 ] / 18.2;
		const sustain = duration * sustainRate;
		const attack = duration * attackRate;
		const decay = duration * decayRate;
		const word = data[ i + 2 ];
		$.sound( freq, sustain, volume, "sawtooth", totalDuration, attack, decay );
		printWord( word, totalDuration );
		totalDuration += duration;
	}
} );

function printWord( word, delay ) {
	printTimeouts.push( setTimeout( function () {
		$.print( word, word.indexOf( "\n" ) === -1 );
	}, delay * 1000 ) );
}

See Also

startGamepad

Starts the gamepad input loop and begins monitoring for gamepad connections.

Syntax

startGamepad();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Connect gamepad and press a button or move an axis to connect" );
$.onGamepadConnected( ( gamepad ) => {
	$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
	$.print( "Game is will start in 3 seconds" );
	$.stopGamepad();
	setTimeout( () => {
		$.print( "Gamepad is now started" );
		$.startGamepad();
	}, 3000 );
} );

run();
function run() {
	const gamepad = $.ingamepad( 0 );
	if( gamepad ) {
		const vAxis = gamepad.getAxis( 0 );
		$.cls();
		$.circle( Math.floor( 300 * ( vAxis / 2 ) ) + 150, 100, 8 );
	}
	requestAnimationFrame( run );
}

See Also

startKeyboard

Starts keyboard input monitoring.

Syntax

startKeyboard();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.stopKeyboard();
$.print( "Keyboard will be enabled in 3 seconds." );
$.onkey( "any", "down", () => {
	$.print( "Key pressed!" );
} );
setTimeout( () => {
	$.print( "Keyboard is enabled" );
	$.startKeyboard();
}, 3000 );

See Also

startMouse

Starts mouse input tracking for this screen.

Syntax

startMouse();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.stopMouse();
$.print( "Mouse will be enabled in 3 seconds." );
$.onmouse( "move", ( mouseData ) => {
	$.setPosPx( mouseData.x, mouseData.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 13 );
	$.print( "+", true );
} );
setTimeout( () => {
	$.setPos( 0, 1 );
	$.setColor( 7 );
	$.print( "Mouse is enabled" );
	$.startMouse();
}, 3000 );

See Also

startTouch

Starts touch input tracking for this screen.

Syntax

startTouch();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.stopTouch();
$.print( "Touch will be enabled in 3 seconds." );
$.ontouch( "move", ( touchData ) => {
	const touch = touchData[ 0 ];
	$.setPosPx( touch.x, touch.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 13 );
	$.print( "+", true );
} );
setTimeout( () => {
	$.setPos( 0, 1 );
	$.setColor( 7 );
	$.print( "Touch is enabled" );
	$.startTouch();
}, 3000 );

See Also

stopAudio

Stops audio from an audio pool or all audio pools.

Syntax

stopAudio( audioId );

Description

Parameters

  • audioId? (string)

    Audio pool ID. If null, stops all audio pools.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
let audio = $.loadAudio( "media/sound.wav", null, 1 );
$.ready( function () {
	$.print( "Press any key to hear sound" );
	$.onkey( "any", "down", () => {
		$.playAudio( audio );
		setTimeout( function () {
			$.stopAudio( audio );
		}, 500 );
	} );
} );

See Also

stopGamepad

Stops the gamepad input loop.

Syntax

stopGamepad();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Connect gamepad and press a button or move an axis to connect" );
$.onGamepadConnected( ( gamepad ) => {
	$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
	setTimeout( () => {
		$.print( "Gamepad is now stopped" );
		$.stopGamepad();
	}, 3000 );
} );

run();
function run() {
	const gamepad = $.ingamepad( 0 );
	if( gamepad ) {
		const vAxis = gamepad.getAxis( 0 );
		$.cls();
		$.print( "Game will stop in 3 seconds" );
		$.circle( Math.floor( 300 * ( vAxis / 2 ) ) + 150, 100, 8 );
	}
	requestAnimationFrame( run );
}

See Also

stopKeyboard

Stops keyboard input monitoring.

Syntax

stopKeyboard();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Keyboard will be stopped in 3 seconds." );
$.onkey( "any", "down", () => {
	$.print( "Key pressed!" );
} );
setTimeout( () => {
	$.print( "Keyboard is now stopped" );
	$.stopKeyboard();
}, 3000 );

See Also

stopMouse

Stops mouse input tracking for this screen.

Syntax

stopMouse();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Mouse will be stopped in 3 seconds." );
$.onmouse( "move", ( mouseData ) => {
	$.setPosPx( mouseData.x, mouseData.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 13 );
	$.print( "+", true );
} );
setTimeout( () => {
	$.setPos( 0, 1 );
	$.setColor( 7 );
	$.print( "Mouse is stopped" );
	$.stopMouse();
}, 3000 );

See Also

stopPlay

Stops playing music tracks.

Syntax

stopPlay( trackId );

Description

Parameters

  • trackId? (number)

    Track ID to stop. If null, stops all tracks.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Press any key to hear sound" );
$.onkey( "any", "down", () => {
	$.play( "T120 O4 L4 CDEF GAB>C ABCDEFG" );
	setTimeout( () => {
		$.stopPlay();
	}, 500 );
} );

See Also

stopSound

Stops a playing sound or all sounds.

Syntax

stopSound( soundId );

Description

Parameters

  • soundId? (string)

    Sound ID returned from sound(). If null, stops all sounds.

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Press any key to hear sound" );
$.onkey( "any", "down", () => {
	const soundId = $.sound( 440, 5 );
	setTimeout( () => {
		$.stopSound();
	}, 500 );
} );

See Also

stopTouch

Stops touch input tracking for this screen.

Syntax

stopTouch();

Description

Returns

  • void

    This function does not return a value.

Example

$.screen( "300x200" );
$.print( "Touch will be stopped in 3 seconds." );
$.ontouch( "move", ( touchData ) => {
	const touch = touchData[ 0 ];
	$.setPosPx( touch.x, touch.y );
	var pos = $.getPos();
	$.setPos( pos.col, pos.row );
	$.setColor( 13 );
	$.print( "+", true );
} );
setTimeout( () => {
	$.setPos( 0, 1 );
	$.setColor( 7 );
	$.print( "Touch is stopped" );
	$.stopTouch();
}, 3000 );

See Also

viewToScreen

Converts a local view point to screen coordinates.

Syntax

viewToScreen( x, y );

Description

Parameters

  • x (number)

    Local x coordinate.

  • y (number)

    Local y coordinate.

Returns

  • PositionPx

    Screen / FBO position { x, y }.

Example

$.screen( "320x200" );
$.pushView( 40, 20, 100, 80 );
const p = $.viewToScreen( 0, 0 );
$.print( p.x + "," + p.y );

See Also

width

Returns the screen or active view width in pixels.

Syntax

width();

Description

Returns

  • number

    Screen or local view width in pixels.

Example

$.screen( "320x200" );
const w = $.width();
$.print( `Screen Width: ${w} ` );
$.print( `Canvas CSS width: ${$.canvas().offsetWidth}` );
$.pushView( 30, 20, 50, 50 );
$.print( `Viewport Width: ${$.width()} ` );
$.popView();

See Also