Pi.js Reference
Version: 2.3 (change)
C
C
D
D
E
E
F
F
G
G
H
H
O
O
R
R
S
S
W
W
No methods match your search yet.
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
Applies a custom shader to the screen 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(color.a - 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
cancelInput
Cancels the current input prompt on this screen.
Syntax
cancelInput();
Description
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.print( "\n" );
$.input( "What is your name? ", null );
$.onKey( "Escape", "down", function () {
$.print( "\nInput Canceled" );
$.cancelInput();
}, true );
See Also
canvas
Returns the HTMLCanvasElement for the current screen.
Syntax
canvas();
Description
Returns
-
HTMLCanvasElement
The canvas DOM element for the current screen.
Example
$.screen( "300x200" );
$.canvas().style.backgroundColor = "purple";
$.print( "\n\nThe background is now purple." );
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", "click", "gamepad").
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" );
createColor
Converts a supported color value into a color object.
Syntax
createColor( color );
Description
Parameters
-
color (any)
Palette index or color value (string, array, object, number).
Returns
-
*Object
A color value object for the converted color.
Example
const red = $.createColor( "red" );
$.print( `[ ${red.array.join( ", " )} ]` );
See Also
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(color.a - 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): color holds RGBA at indices 0-3. Return truthy to keep the modified pixel, or falsy to make it transparent. Copy the buffer to retain it.
-
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
getAllScreens
Returns an array of all screen API objects.
Syntax
getAllScreens();
Description
Returns
-
*Array
Array of screen API objects.
Example
$.screen( "320x200" );
$.screen( "320x200" );
const screens = $.getAllScreens();
$.print( `Number of screens = ${screens.length}` );
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
Resolves to a 2D array [height][width] of indices (default) or color values. Rejects with code SCREEN_REMOVED if the screen is removed before deferred processing completes, or with the original read error.
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
getCols
Returns the number of character columns that fit on the screen.
Syntax
getCols();
Description
Returns
-
number
Number of columns that fit on the screen.
Example
$.screen( "320x200" );
$.setFont( 1 );
const cols = $.getCols();
$.print( `Screen fits ${cols} columns` );
See Also
getDefaultColor
Gets the default foreground color used by new screens.
Syntax
getDefaultColor( 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
$.setDefaultColor( 9 );
$.print( `Default Color Index: ${$.getDefaultColor( true )}` );
$.print( `Default Color Value: [${$.getDefaultColor( false ).array.join( ", " )}]` );
See Also
getDefaultPal
Gets default palette and returns an array with all the color data.
Syntax
getDefaultPal( include0 );
Description
Parameters
-
include0? (boolean)
If true include palette index 0 (transparent black).
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
Resolves a registered image, direct image source, or screen.
Syntax
getImage( name );
Description
Parameters
-
name (*Many)
Registered image name, Screen, or direct image source.
Returns
-
*HTMLElement
The resolved source, or a canvas containing the screen's pixels.
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)
Finite integer from 0 through the last palette entry.
Returns
-
*PiColor
Color value object if the index is valid; 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
Resolves to a palette index or color value object. Rejects with code SCREEN_REMOVED if the screen is removed before deferred processing completes, or with the original read error.
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, state }.
Example
const plugins = $.getPlugins();
$.screen( "300x200" );
for( const plugin of plugins ) {
$.print( `Plugin: ${plugin.name} (${plugin.version}): ${plugin.state}` );
$.print( `Description: ${plugin.description}` );
$.print();
}
See Also
getPos
Gets the current print cursor position as column and row.
Syntax
getPos();
Description
Returns
-
Position
Object with col and row properties (0-indexed).
Example
$.screen( "320x200" );
$.setFont( 1 );
$.print( "Hello" );
const pos = $.getPos();
$.print( `Cursor at column ${pos.col}, row ${pos.row}` );
See Also
getPosPx
Gets the current print cursor position in pixels.
Syntax
getPosPx();
Description
Returns
-
PositionPx
Object with x and y properties in pixels.
Example
$.screen( "320x200" );
$.setFont( 1 );
$.print( "Hello" );
const pos = $.getPosPx();
$.print( `Cursor at ${pos.x}, ${pos.y} pixels` );
See Also
getRows
Returns the number of character rows that fit on the screen.
Syntax
getRows();
Description
Returns
-
number
Number of rows that fit on the screen.
Example
$.screen( "320x200" );
$.setFont( 1 );
const rows = $.getRows();
$.print( `Screen fits ${rows} rows` );
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 read. If omitted or null, returns every connected pad.
Returns
-
*Many
The pad for the index, or null when none has it or polling is stopped; with no index, an array of every connected pad, empty while polling is stopped.
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() {
const keys = $.inKey();
$.cls();
$.print( "Press any key" );
for( const keyData of keys ) {
$.print( "--------------------------" );
$.print( "key: " + keyData.key );
$.print( "location: " + keyData.location );
$.print( "code: " + keyData.code );
}
requestAnimationFrame( run );
}
See Also
inMouse
Gets the current mouse state and starts tracking if needed.
Syntax
inMouse();
Description
Returns
-
MouseData | null
Frozen mouse data of the latest event, or null before it and while stopped.
Example
$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
const mouse = $.inMouse();
// Draw while a button is held; there is no mouse data before the first event
if( mouse !== null && mouse.buttons > 0 ) {
$.setColor( 14 );
$.line( mouse.lastX, mouse.lastY, mouse.x, mouse.y );
}
requestAnimationFrame( run );
}
See Also
inPress
Gets the current press state (mouse or touch) and starts tracking if needed.
Syntax
inPress();
Description
Returns
-
PressData | null
Frozen press data of the primary pointer, from the mouse or touch, or null.
Example
$.screen( "300x200" );
$.setPinchZoom( false );
requestAnimationFrame( run );
function run() {
const press = $.inPress();
// Draw while pressed; there is no press data before the first event
if( press !== null && press.buttons > 0 ) {
$.setColor( 15 );
$.line( press.lastX, press.lastY, press.x, press.y );
}
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, or null if cancelled.
-
cursor? (string)
Cursor character to display. Omitted or empty, it is character code 219, which the built-in fonts draw as a block.
-
isNumber? (boolean)
If true, only accepts a number and resolves with a number.
-
isInteger? (boolean)
If true, only accepts an integer, with no decimal point, and resolves with a number, with or without isNumber.
-
allowNegative? (boolean)
If true, a numeric input accepts a leading minus sign.
-
maxLength? (number)
Maximum length of the input, at least 1, including a minus sign. Null or omitted for no limit.
Returns
-
Promise
Promise that resolves with the input value, a number for numeric input, or null if cancelled.
Example
$.screen( "300x200" );
$.input( "Enter your name: ", async ( name ) => {
$.print( `Hello, ${name}!` );
const age = await $.input( {
"prompt": "Enter age: ",
"isInteger": true,
"maxLength": 3
} );
$.print( `You are ${age} years old.` );
} );
See Also
inTouch
Gets the current touch state and starts tracking if needed.
Syntax
inTouch();
Description
Returns
-
*Array
Touches still down; empty when none is down.
Example
$.screen( "300x200" );
requestAnimationFrame( run );
function run() {
$.cls();
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
Loads an audio file for playback with playAudio.
Syntax
loadAudio( src, name, stream );
Description
Parameters
-
src (string)
Audio file URL (e.g., 'sound.mp3', 'audio/beep.wav').
-
name? (string)
A unique name to use as the audio ID. If omitted, an ID is generated.
-
stream? (boolean)
True to stream the file through a media element instead of decoding it into memory (default: false).
Returns
-
string
Audio ID for use with playAudio, stopAudio, pauseAudio, resumeAudio, and removeAudio.
Example
$.screen( "300x200" );
$.loadAudio( "media/bomb.wav", "bomb" );
$.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); an integer of at least 1.
-
height (number)
Character height in pixels (glyph height, excluding margin); an integer of at least 1.
-
margin? (number)
Margin around each character cell in pixels; an integer of 0 or more. 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, 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.
-
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, 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; an integer of 0 or more. Defaults to 0.
-
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 to remove. If omitted or null, removes every click handler.
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
offGamepad
Removes a gamepad connection or disconnection callback.
Syntax
offGamepad( mode, fn );
Description
Parameters
-
mode? (string | null)
'connect' or 'disconnect'. If omitted or null, fn is removed from both modes.
-
fn? (function)
Callback to remove. If omitted or null, every callback of the mode is removed.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
function onConnect( gamepad ) {
$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
// Only the first connection is announced
$.offGamepad( "connect", onConnect );
}
$.onGamepad( "connect", onConnect );
See Also
offKey
Removes a key event handler.
Syntax
offKey( key, mode, fn );
Description
Parameters
-
key (*Many)
Key code, key value, "any", or combination array of the handlers to remove.
-
mode? (string | null)
Event mode ("up" or "down"). If omitted or null, fn is removed from both modes.
-
fn? (function)
Callback to remove. If omitted, every handler of the mode is removed.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.print( "Move with the arrow keys." );
$.print( "Press Escape to stop." );
$.onKey( "ArrowLeft", "down", moveLeft );
$.onKey( "ArrowRight", "down", moveRight );
$.onKey( "Escape", "down", stop );
function moveLeft() {
$.print( "Left" );
}
function moveRight() {
$.print( "Right" );
}
// Remove each handler, then the Escape handler itself
function stop() {
$.print( "Stopped." );
$.offKey( "ArrowLeft", "down", moveLeft );
$.offKey( "ArrowRight", "down", moveRight );
$.offKey( "Escape", "down" );
}
See Also
offMouse
Removes a mouse event handler.
Syntax
offMouse( mode, fn );
Description
Parameters
-
mode? (string | null)
Mode ('down', 'up', or 'move'); if omitted or null, fn is removed from every mode.
-
fn? (function)
Callback function to remove. If omitted or null, removes every handler of the 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 | null)
Mode ('down', 'up', or 'move'); if omitted or null, fn is removed from every mode.
-
fn? (function)
Callback function to remove. If omitted or null, removes every handler of the 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 | null)
Mode ('down', 'up', or 'move'); if omitted or null, fn is removed from every mode.
-
fn? (function)
Callback function to remove. If omitted or null, removes every handler of the 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( "up", touchStop, true );
// Touch move function receives the touches that moved 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 the touches that ended 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
offWheel
Removes a wheel event handler.
Syntax
offWheel( fn );
Description
Parameters
-
fn? (function)
Callback function to remove. If omitted or null, removes every wheel handler.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
let turns = 0;
const handler = ( wheelData ) => {
turns += 1;
$.print( `Wheel ${turns}: ${wheelData.deltaY}` );
if( turns === 5 ) {
$.offWheel( handler );
$.print( "Wheel handler removed; the page scrolls again." );
}
};
$.onWheel( handler );
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).
-
once? (boolean)
If true, this registration is removed before the callback's first run.
-
hitBox? (HitBox)
Optional area the press and release must both be inside. Defaults to the 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
onGamepad
Registers a callback function for gamepad connections or disconnections.
Syntax
onGamepad( mode, fn, once );
Description
Parameters
-
mode (string)
Event mode: 'connect' or 'disconnect'.
-
fn (function)
Callback that receives GamepadData or GamepadDisconnectData, by mode.
-
once? (boolean)
If true, this registration is removed before the callback's first run.
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" );
$.onGamepad( "connect", ( gamepad ) => {
$.print( `Gamepad ${gamepad.index} connected: ${gamepad.id}` );
} );
$.onGamepad( "disconnect", ( data ) => {
$.print( `Gamepad ${data.index} disconnected: ${data.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 the key data, or an array of key data for a combination.
-
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" );
// Game controls use codes, which name the physical key on every layout
$.onKey( "KeyW", "down", () => {
$.print( "Up" );
} );
$.onKey( "Space", "down", () => {
$.print( "Jump" );
} );
// Key combination
$.onKey( [ "ControlLeft", "KeyS" ], "down", ( keys ) => {
$.print( "Ctrl+S pressed!" );
} );
// One-time handler
$.onKey( "Enter", "down", () => {
$.print( "Enter 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).
-
once? (boolean)
If true, this registration is removed before the callback's first run.
-
hitBox? (HitBox)
Optional area; the callback runs only for events inside it.
-
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).
-
once? (boolean)
If true, this registration is removed before the callback's first run.
-
hitBox? (HitBox)
Optional area; the callback runs only for presses inside it.
-
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: 'down', 'up', or 'move'.
-
fn (function)
Callback function that receives (touches, customData) with the changed touches.
-
once? (boolean)
If true, this registration is removed before the callback's first run.
-
hitBox? (HitBox)
Optional area; the callback receives only the changed touches inside it.
-
customData? (any)
Optional custom data passed to the callback function.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.onTouch( "down", ( touches ) => {
for( const touch of touches ) {
$.setPosPx( touch.x, touch.y );
$.print( `Touch ${touch.id} started` );
}
} );
$.onTouch( "move", ( touches ) => {
$.setColor( 3 );
for( const touch of touches ) {
$.line( touch.lastX, touch.lastY, touch.x, touch.y );
}
$.setColor( 7 );
} );
See Also
onWheel
Registers a callback function for mouse wheel and trackpad scroll events.
Syntax
onWheel( fn, once, hitBox, customData );
Description
Parameters
-
fn (function)
Callback function that receives (wheelData, customData).
-
once? (boolean)
If true, this registration is removed before the callback's first run.
-
hitBox? (HitBox)
Optional area the wheel event must be inside. Defaults to the whole canvas.
-
customData? (any)
Optional custom data passed to the callback function.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
let zoom = 1;
$.onWheel( ( wheelData ) => {
// Zoom in when the wheel turns up, and out when it turns down
zoom = Math.min( Math.max( zoom - wheelData.deltaY / 500, 0.25 ), 4 );
$.cls();
$.print( `Zoom: ${zoom.toFixed( 2 )}` );
} );
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
pauseAudio
Pauses an audio instance, every instance of an audio ID, or all audio.
Syntax
pauseAudio( id );
Description
Parameters
-
id? (number | string)
Instance ID, or audio ID to pause all its instances. If omitted, pauses all audio.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
const music = $.loadAudio( "media/sound.wav" );
let instance = null;
let paused = false;
$.ready( function () {
$.print( "Press any key to play, then to pause and resume" );
$.onKey( "any", "down", () => {
if( instance === null ) {
instance = $.playAudio( { "audioId": music, "loop": true } );
} else if( paused ) {
$.resumeAudio( instance );
paused = false;
} else {
$.pauseAudio( instance );
paused = true;
}
} );
} );
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
Track ID for use with stopPlay.
Example
$.screen( "300x200" );
const tracks = [
"T120 O3 L4 GAB>C",
"T120 O3 L4 MS GAB>C ML GAB>C",
"T120 O4 L2 C, E, G",
"T120 L8 WN MA0 MD20 MH0 MR20 C C C P8 C C",
"[[0,1,0,-1],[0,0,0,0]] T120 O3 L4 MP-100 G MP100 A MP0 B>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 += 2500;
}
} );
See Also
playAudio
Plays loaded audio as a new instance and returns its instance ID.
Syntax
playAudio( audioId, volume, startTime, duration, loop, playbackRate, pan, delay );
Description
Parameters
-
audioId (string)
Audio ID returned from loadAudio.
-
volume? (number)
Volume (0-1, default: 1).
-
startTime? (number)
Offset into the file in seconds (default: 0).
-
duration? (number)
Seconds of the file to play, including every loop pass (default: 0 = to the end, or forever when looping).
-
loop? (boolean)
Loop the whole file (default: false).
-
playbackRate? (number)
Speed and pitch: 0.0625-16 for decoded audio, 0.25-4 for streamed audio (default: 1).
-
pan? (number)
Stereo position from -1 (left) to 1 (right) (default: 0).
-
delay? (number)
Seconds before playback starts (default: 0).
Returns
-
number
Instance ID for use with stopAudio, pauseAudio, resumeAudio, and setAudio.
Example
$.screen( "300x200" );
const bomb = $.loadAudio( "media/bomb.wav" );
$.ready( function () {
$.print( "Press any key to play bomb sound." );
$.onKey( "any", "down", () => {
$.print( "BOOM ", true );
$.playAudio( {
"audioId": bomb, "playbackRate": 0.75 + Math.random() * 0.5,
"pan": Math.random() * 2 - 1
} );
}, false, true );
} );
See Also
polygon
Draws a closed polygon outline with an optional fill.
Syntax
polygon( points, fillColor );
Description
Parameters
-
points (Array | TypedArray)
Flat coordinates or point objects describing one closed path.
-
fillColor? (any)
Optional palette index or Pi.js color value; null draws only the outline.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.setColor( 15 );
$.polygon( [ 20, 20, 140, 30, 100, 120, 40, 90 ], 4 );
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
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 to undefined when ready, after invoking the optional callback. Rejects with the original thrown value if the callback throws synchronously. Callback return values are ignored.
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 loaded audio 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" );
$.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. Required in the global form; the declaration marks it optional because each screen's own removeScreen() takes none.
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
resumeAudio
Resumes a paused audio instance, every instance of an audio ID, or all audio.
Syntax
resumeAudio( id );
Description
Parameters
-
id? (number | string)
Instance ID, or audio ID to resume all its instances. If omitted, resumes all paused audio.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
const music = $.loadAudio( "media/sound.wav" );
let instance = null;
$.ready( function () {
$.print( "Hold any key to play the music" );
$.onKey( "any", "down", () => {
if( instance === null ) {
instance = $.playAudio( { "audioId": music, "loop": true } );
} else {
$.resumeAudio( instance );
}
} );
$.onKey( "any", "up", () => {
if( instance !== null ) {
$.pauseAudio( instance );
}
} );
} );
See Also
screen
Creates a new screen (canvas) with specified dimensions and aspect ratio.
Syntax
screen( aspect, container, isOffscreen, resizeCallback, parent, noCss );
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 to share drawing with. Only for an offscreen screen. Makes drawImage from that screen faster.
-
noCss? (boolean)
If true, Pi.js does not set canvas or page styles. Supply the canvas layout in your own CSS.
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., { "color": 2, "font": 1 }).
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 the keys whose default browser behavior is prevented.
Syntax
setActionKeys( keys );
Description
Parameters
-
keys (*Array)
Array of key codes or key values that become the action keys.
Returns
-
void
This function does not return a value.
Example
$.screen( "200x200" );
$.setActionKeys( [ "ControlLeft", "KeyS" ] );
setInterval( function () {
const keys = $.inKey();
$.cls();
$.print( "Press Ctrl+S." );
if( $.inKey( "Control" ) ) {
$.print( "Control key is pressed." );
} else {
$.print( "Control key is not pressed." );
}
for( const keyData of keys ) {
$.print( "--------------------------" );
$.print( "key: " + keyData.key );
$.print( "location: " + keyData.location );
$.print( "code: " + keyData.code );
}
}, 60 );
See Also
setAudio
Changes the volume, playback rate, or pan of an audio instance.
Syntax
setAudio( instanceId, volume, playbackRate, pan );
Description
Parameters
-
instanceId (number)
Instance ID returned from playAudio.
-
volume? (number)
Volume (0-1).
-
playbackRate? (number)
Speed and pitch within the instance's mode range.
-
pan? (number)
Stereo position from -1 (left) to 1 (right).
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
const engine = $.loadAudio( "media/sound.wav" );
let instance = null;
let rate = 1;
$.ready( function () {
$.print( "Press up and down to change the pitch" );
$.onKey( "any", "down", key => {
if( instance === null ) {
instance = $.playAudio( { "audioId": engine, "loop": true, "volume": 0.5 } );
}
if( key.key === "ArrowUp" ) {
rate = Math.min( rate * 1.1, 4 );
} else if( key.key === "ArrowDown" ) {
rate = Math.max( rate / 1.1, 0.25 );
}
$.setAudio( { "instanceId": instance, "playbackRate": rate } );
} );
} );
See Also
setBgColor
Sets the canvas background color.
Syntax
setBgColor( 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" );
$.setBgColor( "navy" );
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
setBusVolume
Sets the volume of one sound bus.
Syntax
setBusVolume( bus, volume );
Description
Parameters
-
bus (string)
'sfx', 'music', 'audio', or 'master'.
-
volume (number)
Volume, 0-1.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.print( "Press M to toggle music" );
let isMuted = false;
$.play( "T120 L8 O4 C E G E C E G E" );
$.onKey( "KeyM", "down", () => {
isMuted = !isMuted;
if( isMuted ) {
$.setBusVolume( "music", 0 );
} else {
$.setBusVolume( "music", 1 );
}
} );
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)
Numeric integer palette index, CSS/hex string, RGB/RGBA array, or color object.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.setColor( 9 );
$.rect( 100, 50, 100, 100 );
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
setContextMenu
Enables or disables the right-click context menu.
Syntax
setContextMenu( isEnabled );
Description
Parameters
-
isEnabled (boolean)
If true, the context menu opens. If false, it is suppressed.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.print( "Right-click to open the context menu." );
$.setContextMenu( true );
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)
Numeric integer palette index, CSS/hex string, RGB/RGBA array, or color object.
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 shader used to present the screen to the canvas.
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(color.a - 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
Updates uniforms on the active display shader.
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(clamp(color.rgb * u_gain, 0.0, color.a), color.a);
}` );
$.screen( "320x200" );
$.setColor( 14 );
$.circle( 160, 100, 40, 4 );
$.setDisplayShader( tint, { "u_gain": 1 } );
$.setDisplayShaderUniforms( { "u_gain": 0.5 } );
See Also
setFont
Sets the font for the current screen.
Syntax
setFont( fontId );
Description
Parameters
-
fontId (number)
The id of the font to set. The default fonts loaded are.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
for( var i = 0; i < 4; i++ ) {
$.setFont( i );
$.print( "Font - " + i );
}
See Also
setGamepadDeadZone
Sets the dead zone for gamepad sticks and axes.
Syntax
setGamepadDeadZone( deadZone );
Description
Parameters
-
deadZone (number)
Dead zone from 0 to under 1 (0 = no dead zone). The default is 0.2.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.setGamepadDeadZone( 0.15 );
run();
function run() {
const gamepad = $.inGamepad( 0 );
$.cls();
if( gamepad ) {
// The left stick moves the circle in any direction
const x = gamepad.getAxis( 0 );
const y = gamepad.getAxis( 1 );
$.circle( Math.floor( 150 + x * 100 ), Math.floor( 100 + y * 80 ), 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 on the screen canvas.
Syntax
setPinchZoom( isEnabled );
Description
Parameters
-
isEnabled (boolean)
If true, a pinch on the canvas zooms the page. If false, it does not.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.setPinchZoom( true ); // Let a pinch on the canvas zoom the page
$.setPinchZoom( false ); // Keep every touch on the canvas for the game
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; a number greater than 0.
-
scaleHeight? (number)
Vertical scale factor; a number greater than 0.
-
padX? (number)
Extra horizontal padding between characters in pixels; an integer of 0 or more. Defaults to 0.
-
padY? (number)
Extra vertical padding between lines in pixels; an integer of 0 or more. 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
setSoundLimiter
Turns the output limiter on or off.
Syntax
setSoundLimiter( enabled );
Description
Parameters
-
enabled (boolean)
True to limit output (the default), false to bypass the limiter.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
$.print( "Press any key to hear a chord without the limiter" );
$.setSoundLimiter( false );
$.setVolume( 0.2 );
$.onKey( "any", "down", () => {
$.sound( 262, 1, 0.5 );
$.sound( 330, 1, 0.5 );
$.sound( 392, 1, 0.5 );
} );
See Also
setVolume
Sets the master volume for all sounds, music, and audio.
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 synthesized sound with an ADSR envelope using Web Audio API.
Syntax
sound( frequency, duration, volume, oType, delay, attackTime, decayTime, sustainLevel, releaseTime, pan, frequencyEnd );
Description
Parameters
-
frequency? (number)
Frequency in Hz; no effect on noise (default: 440).
-
duration? (number)
Gate length in seconds: how long the sound is held before the release begins (default: 1).
-
volume? (number)
Peak volume 0-1 (default: 1).
-
oType? (*Many)
Oscillator type: 'triangle', 'sine', 'square', 'sawtooth', 'white' or 'pink' noise, a source type added by a plugin (such as 'periodic' from sound-advanced), or custom wavetable array [[realArray], [imagArray]] (default: 'triangle').
-
delay? (number)
Delay before playing in seconds (default: 0).
-
attackTime? (number)
Seconds from silence to the peak volume (default: 0).
-
decayTime? (number)
Seconds from the peak to the sustain level (default: 0).
-
sustainLevel? (number)
Fraction of the peak volume held until duration ends, 0-1 (default: 1).
-
releaseTime? (number)
Seconds from the sustain level to silence after duration ends (default: 0.1).
-
pan? (number)
Stereo position from -1 (left) to 1 (right) (default: 0).
-
frequencyEnd? (number)
Frequency in Hz to sweep to exponentially over duration; no effect on noise (default: no sweep).
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 = [];
let totalDuration = 0;
$.screen( "300x200" );
$.print( "Press any key to hear the song" );
$.onKey( "any", "down", () => {
for( let i = 0; i < data.length; i += 3 ) {
const length = data[ i + 1 ] / 18.2;
const word = data[ i + 2 ];
$.sound( {
"frequency": data[ i ],
"duration": length * 0.9,
"volume": 0.15,
"oType": "sawtooth",
"delay": totalDuration,
"attackTime": length * 0.01,
"decayTime": length * 0.3,
"sustainLevel": 0.7,
"releaseTime": length * 0.1
} );
printWord( word, totalDuration );
totalDuration += length;
}
} );
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" );
$.onGamepad( "connect", ( 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", ( touches ) => {
const touch = touches[ 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 an audio instance, every instance of an audio ID, or all audio.
Syntax
stopAudio( id );
Description
Parameters
-
id? (number | string)
Instance ID, or audio ID to stop all its instances. If omitted, stops all audio.
Returns
-
void
This function does not return a value.
Example
$.screen( "300x200" );
const audio = $.loadAudio( "media/sound.wav" );
$.ready( function () {
$.print( "Press any key to hear sound" );
$.onKey( "any", "down", () => {
const instance = $.playAudio( audio );
setTimeout( function () {
$.stopAudio( instance );
}, 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" );
$.onGamepad( "connect", ( 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( soundId );
}, 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", ( touches ) => {
const touch = touches[ 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
vibrateGamepad
Rumbles a gamepad's vibration motors.
Syntax
vibrateGamepad( gamepadIndex, duration, strong, weak );
Description
Parameters
-
gamepadIndex (number)
Index of the pad to rumble.
-
duration (number)
Rumble length in milliseconds.
-
strong? (number)
Strong (low-frequency) motor magnitude from 0 to 1. The default is 1.
-
weak? (number)
Weak (high-frequency) motor magnitude from 0 to 1. The default is 1.
Returns
-
boolean
True when the pad supports the dual-rumble effect and it was started.
Example
$.screen( "300x200" );
$.print( "Press the south button to rumble" );
function run() {
const gamepad = $.inGamepad( 0 );
if( gamepad && gamepad.getButtonJustPressed( "south" ) ) {
if( !$.vibrateGamepad( 0, 200, 1, 0.5 ) ) {
$.print( "This gamepad cannot rumble in this browser" );
}
}
requestAnimationFrame( run );
}
run();
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();