Codetoy.io
Spiders

AssemblyScript Documentation

Codetoy supports a subset of TypeScript named AssemblyScript that can compile directly to WebAssembly (WASM). For a list of feature parity with TypeScript see this page assemblyscript.org/status

To give you an idea of what is possible:

import { fill, triangle, polygon, circle, rect } from "codetoy/canvas"
import * as screen from "codetoy/screen"

export function update(): void {
  // Clear the background color to soft grey
  fill(20, 20, 30)
  rect(0, 0, screen.width(), screen.height())

  // Draw triangle
  fill(255, 100, 100) // fill color
  triangle(
    screen.centerX() - 150, 100,
    screen.centerX() - 250, 200,
    screen.centerX() - 50, 200
  )

  // Create a pentagon
  const pentagon = new Array<f64>()
  for (let i = 0; i < 5; i++) {
    const angle = (i as f64 / 5.0) * 2.0 * Math.PI
    pentagon.push(screen.centerX() + Math.cos(angle) * 60)
    pentagon.push(screen.centerY() + Math.sin(angle) * 60)
  }

  // Draw the pentagon
  fill(100, 200, 150)
  polygon(pentagon)

  // Draw circle
  fill(150, 100, 255)
  circle(screen.centerX() + 150, screen.centerY(), 50)
}

More examples can be found at the bottom of the page here

Canvas

import * as canvas from "codetoy/canvas"

State Stack

canvas.reset()

canvas.push()

canvas.pop()

Color State

canvas.fill(r, g, b, a = 1.0)

canvas.stroke(r, g, b, a = 1.0)

Line State

canvas.lineWidth(width: number)

canvas.lineJoin("round" | "bevel" | "miter")

canvas.lineMiterLimit(limit: number)

canvas.lineCap("butt" | "round" | "square")

Shape Drawing

canvas.rect(x, y, w, h, r = 0)

canvas.circle(x, y, radius)

canvas.line(x1, y1, x2, y2)

canvas.ellipse(x, y, w, h)

canvas.triangle(x1, y1, x2, y2, x3, y3)

canvas.polygon(number[] points) (eg. x1,y1, x2,y2, ...)

Transform

canvas.scale(x, y)

canvas.rotate(radians)

canvas.translate(x, y)

canvas.resetTransform()

Advanced Drawing

canvas.beginPath()

canvas.moveTo(x, y)

canvas.lineTo(x, y)

canvas.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

canvas.quadraticCurveTo(cpx, cpy, x, y)

canvas.closePath()

canvas.fillPath()

canvas.strokePath()

Text

canvas.font(family, size, weight = "normal")

canvas.text(text, x, y)

canvas.measureText(text) → number (returns width of text)

Input

import * as input from "codetoy/input"

Mouse

input.mouseX() and input.mouseY() → number

input.isMouseDown(button: number) → bool (0=left, 1=middle, 2=right)

export function onMouseDown(key: string) {}

export function onMouseUp(key: string) {}

Keyboard

input.isKeyDown(key: string) → bool (if the key is being held down)

export function onKeyDown(key: string) {}

export function onKeyUp(key: string) {}

Screen

import * as screen from "codetoy/screen"

screen.width() and screen.height() → number

screen.centerX() and screen.centerY() → number

Time

import * as time from "codetoy/time"

time.deltaTime() → number (seconds since last frame)

time.elapsedTime() -> number

Console

The console module is global by default and does not need imported

console.log(message: string)

console.warn(message: string)

console.error(message: string)

API Examples

Package "codetoy/canvas"

reset(): void

Clear the entire screen and any previous state for subsequent drawing operations.

Example:

import { reset } from "codetoy/canvas"

reset()

fill(r, g, b, a: f64 = 1.0): void

Sets the fill color for subsequent drawing operations.

Parameters:

  • r (f64): Red channel (0-255)
  • g (f64): Green channel (0-255)
  • b (f64): Blue channel (0-255)
  • a (f64, optional): Alpha/opacity (0-1, default: 1.0)

Example:

import { fill, rect } from "codetoy/canvas"

fill(255, 0, 0, 0.8)  // Semi-transparent red
rect(50, 50, 100, 100)

rect(x, y, width, height, r: f64 = 0.0): void

Draws a rectangle at the specified position with optional rounded corners.

Parameters:

  • x (f64): X coordinate of top-left corner
  • y (f64): Y coordinate of top-left corner
  • width (f64): Width of rectangle
  • height (f64): Height of rectangle
  • r (f64, optional): Corner radius for rounding (default: 0)

Example:

import { fill, rect } from "codetoy/canvas"

fill(0, 150, 255)
rect(100, 100, 200, 150, 10)  // Blue rounded rectangle

circle(x, y, radius: f64): void

Draws a circle at the specified position.

Parameters:

  • x (f64): X coordinate of circle center
  • y (f64): Y coordinate of circle center
  • radius (f64): Circle radius

Example:

import { fill, circle } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(100, 255, 100)
circle(screen.width() / 2, screen.height() / 2, 50)  // Green circle in center

ellipse(x, y, w, h: f64): void

Draws an ellipse at the specified position.

Parameters:

  • x (f64): X coordinate of ellipse center
  • y (f64): Y coordinate of ellipse center
  • w (f64): Horizontal radius (half-width)
  • h (f64): Vertical radius (half-height)

Example:

import { fill, ellipse } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(255, 200, 0)
ellipse(screen.centerX(), screen.centerY(), 80, 40)  // Yellow ellipse

triangle(x1, y1, x2, y2, x3, y3: f64): void

Draws a triangle with three vertices.

Parameters:

  • x1 (f64): X coordinate of first vertex
  • y1 (f64): Y coordinate of first vertex
  • x2 (f64): X coordinate of second vertex
  • y2 (f64): Y coordinate of second vertex
  • x3 (f64): X coordinate of third vertex
  • y3 (f64): Y coordinate of third vertex

Example:

import { fill, triangle } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(255, 100, 50)
triangle(screen.centerX(), 50, screen.centerX() - 100, screen.height() - 50, screen.centerX() + 100, screen.height() - 50)

polygon(points: f64[]): void

Draws a polygon defined by an array of vertex coordinates.

Parameters:

  • points (f64[]): Array of coordinates in the format [x1, y1, x2, y2, x3, y3, ...]

Example:

import { fill, polygon } from "codetoy/canvas"

const vertices = new Array<f64>()

// x__________      y__________
vertices.push(100); vertices.push(100)
vertices.push(200); vertices.push(50)
vertices.push(250); vertices.push(150)
vertices.push(150); vertices.push(200)

fill(100, 200, 150)
polygon(vertices)

font(family: string, size: f64, weight: string = "normal"): void

Sets the font family, size, and weight for subsequent text drawing operations as described in https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font

Parameters:

  • family (string): Font family name (e.g., "Arial", "Courier", "Georgia")
  • size (f64): Font size in pixels
  • weight (string, optional): Font weight (default: "normal"). Common values: "normal", "bold", "lighter", "100" - "900"

Example:

import { font, text } from "codetoy/canvas"

font("Arial", 24, "bold")
text("Hello World", 50, 50)

text(content: string, x: f64, y: f64): void

Draws text at the specified position using the current font and fill color.

Parameters:

  • content (string): The text to draw
  • x (f64): X coordinate of text position
  • y (f64): Y coordinate of text position

Example:

import { fill, font, text } from "codetoy/canvas"

fill(0, 0, 0)
font("Arial", 20)
text("Score: 100", 10, 30)

measureText(content: string): f64

Returns the width of a piece of text.

Parameters:

  • content (string): The text to measure

Example:

import { fill, font, text, measureText } from "codetoy/canvas"

fill(0, 0, 0)
font("Arial", 20)
text("Score: 100", 10, 30)
const width = measureText("Score: 100");
text("Lives: 100", 14 + width, 30)

Events

export function update(): void

Fired every frame. Use this for animations and game logic.

Example:

import { fill, circle, reset } from "codetoy/canvas"
import * as input from "codetoy/input"

export function update(): void {
  reset()
  fill(255, 100, 0)
  circle(input.mouseX(), input.mouseY(), 20)  // Follow cursor
}

export function onKeyDown(key: string): void

Fired when a key is pressed.

Parameters:

Example:

export function onKeyDown(key: string): void {
  console.log("Key pressed: " + key)
}

export function onKeyUp(key: string): void

Fired when a key is released.

Parameters:

Example:

export function onKeyUp(key: string): void {
  console.log("Key released: " + key)
}

export function onMouseDown(button: i32): void

Fired when a mouse button is pressed.

Parameters:

  • button (i32): 0 = left, 1 = middle, 2 = right

Example:

export function onMouseDown(button: i32): void {
  console.log("Mouse down: " + button)
}

export function onMouseUp(button: i32): void

Fired when a mouse button is released.

Parameters:

  • button (i32): 0 = left, 1 = middle, 2 = right

Example:

export function onMouseUp(button: i32): void {
  console.log("Mouse up: " + button)
}

export function resize(width: f64, height: f64): void

Fired whenever the canvas is resized. Use this instead of calling screen.width() and screen.height() every frame for better performance.

Example:

import { fill, circle } from "codetoy/canvas"
import * as screen from "codetoy/screen"

var centerX = screen.width() / 2
var centerY = screen.height() / 2

// Instead of calling `screen.width()` and `screen.height()` each frame (which is slower),
// we can detect when the screen changes size
export function resize(width: f64, height: f64): void {
  centerX = width / 2
  centerY = height / 2
}

Console

console.log(message: string): void

Logs a message to the console.

Parameters:

  • message (string): The message to log

Example:

console.log("Application started")

console.warn(message: string): void

Logs a warning message to the console.

Parameters:

  • message (string): The warning message

Example:

console.warn("Performance may be degraded")

console.error(message: string): void

Logs an error message to the console.

Parameters:

  • message (string): The error message

Example:

console.error("Invalid input detected")

Package "codetoy/input"

Package for getting the current input state.

input.mouseX(): f64

The current X coordinate of the mouse in canvas space. Updated on mouse movement.

Example:

import * as input from "codetoy/input"

const x = input.mouseX()

input.mouseY(): f64

The current Y coordinate of the mouse in canvas space. Updated on mouse movement.

Example:

import * as input from "codetoy/input"

const y = input.mouseY()

input.isMouseDown(button: i32): bool

Returns whether a mouse button is currently pressed. 0 = left, 1 = middle, 2 = right.

Example:

import * as input from "codetoy/input"

const isLeftDown = input.isMouseDown(0)  // Check if left mouse button is pressed

Package "codetoy/screen"

Package for getting the current screen state.

screen.width(): f64

The current canvas width in pixels. Updates when the window is resized.

Example:

import { fill, ellipse } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(255, 200, 0)
ellipse(screen.width() / 2, screen.height() / 2, 80, 40)  // Yellow ellipse in the center

screen.height(): f64

The current canvas height in pixels. Updates when the window is resized.

Example:

import { fill, ellipse } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(255, 200, 0)
ellipse(screen.width() / 2, screen.height() / 2, 80, 40)  // Yellow ellipse in the center

screen.centerX(): f64

The X coordinate of the canvas center. Equivalent to screen.width() / 2.

Example:

import { fill, circle } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(100, 150, 255)
circle(screen.centerX(), screen.centerY(), 40)  // Circle at center

screen.centerY(): f64

The Y coordinate of the canvas center. Equivalent to screen.height() / 2.

Example:

import { fill, circle } from "codetoy/canvas"
import * as screen from "codetoy/screen"

fill(100, 150, 255)
circle(screen.centerX(), screen.centerY(), 40)  // Circle at center

screen.frameCount(): i32

Returns the number of frames that have elapsed since the application started.

Example:

import * as screen from "codetoy/screen"

export function update(): void {
  if (screen.frameCount() % 60 == 0) {
    console.log("One second has passed (at 60 FPS)")
  }
}

screen.fps(): f64

Returns the current frames per second being rendered.

Example:

import { text, font } from "codetoy/canvas"
import * as screen from "codetoy/screen"

export function update(): void {
  font("Arial", 16)
  text("FPS: " + screen.fps().toString(), 10, 20)
}

Package "codetoy/time"

deltaTime(): f64

Returns the elapsed time since the last frame in seconds. Use this to make animations frame-rate independent.

Example:

import { deltaTime } from "codetoy/time"

var x: f64 = 0
var speed: f64 = 100  // pixels per second

export function update(): void {
  x += speed * deltaTime()
}

elapsedTime(): f64

Returns the total elapsed time since the application started in seconds.

Example:

import { elapsedTime } from "codetoy/time"

export function update(): void {
  const time = elapsedTime()
  // Use time for animations or logic
}

Global Math Class

The global Math class provides mathematical constants and functions for calculations.

Constants

  • Math.E: Euler's number (approximately 2.718)
  • Math.LN2: Natural logarithm of 2 (approximately 0.693)
  • Math.LN10: Natural logarithm of 10 (approximately 2.303)
  • Math.LOG2E: Base-2 logarithm of E (approximately 1.443)
  • Math.LOG10E: Base-10 logarithm of E (approximately 0.434)
  • Math.PI: Pi (approximately 3.14159)
  • Math.SQRT1_2: Square root of 0.5 (approximately 0.707)
  • Math.SQRT2: Square root of 2 (approximately 1.414)

Basic Functions

Math.abs(x: f64): f64

Returns the absolute value of a number.

Math.ceil(x: f64): f64

Returns the smallest integer greater than or equal to the given number.

Math.floor(x: f64): f64

Returns the largest integer less than or equal to the given number.

Math.round(x: f64): f64

Returns the value of a number rounded to the nearest integer.

Math.trunc(x: f64): f64

Returns the integer part of a number by removing any fractional digits.

Math.sqrt(x: f64): f64

Returns the square root of a number.

Math.pow(base: f64, exponent: f64): f64

Returns the base raised to the power of the exponent.

Math.max(value1: f64, value2: f64): f64

Returns the largest of two numbers.

Math.min(value1: f64, value2: f64): f64

Returns the smallest of two numbers.

Math.random(): f64

Returns a random number between 0 (inclusive) and 1 (exclusive).

Trigonometric Functions

Math.sin(x: f64): f64

Returns the sine of a number (in radians).

Math.cos(x: f64): f64

Returns the cosine of a number (in radians).

Math.tan(x: f64): f64

Returns the tangent of a number (in radians).

Math.asin(x: f64): f64

Returns the arcsine of a number (in radians).

Math.acos(x: f64): f64

Returns the arccosine of a number (in radians).

Math.atan(x: f64): f64

Returns the arctangent of a number (in radians).

Math.atan2(y: f64, x: f64): f64

Returns the arctangent of the quotient of its arguments (in radians). Useful for calculating angles.

Hyperbolic Functions

Math.sinh(x: f64): f64

Returns the hyperbolic sine of a number.

Math.cosh(x: f64): f64

Returns the hyperbolic cosine of a number.

Math.tanh(x: f64): f64

Returns the hyperbolic tangent of a number.

Math.asinh(x: f64): f64

Returns the inverse hyperbolic sine of a number.

Math.acosh(x: f64): f64

Returns the inverse hyperbolic cosine of a number.

Math.atanh(x: f64): f64

Returns the inverse hyperbolic tangent of a number.

Exponential and Logarithmic Functions

Math.exp(x: f64): f64

Returns E raised to the power of a number.

Math.expm1(x: f64): f64

Returns E raised to the power of a number minus 1.

Math.log(x: f64): f64

Returns the natural logarithm of a number.

Math.log10(x: f64): f64

Returns the base-10 logarithm of a number.

Math.log2(x: f64): f64

Returns the base-2 logarithm of a number.

Math.log1p(x: f64): f64

Returns the natural logarithm of 1 plus a number.

Other Functions

Math.sign(x: f64): f64

Returns the sign of a number: -1, 0, or 1.

Math.hypot(value1: f64, value2: f64): f64

Returns the square root of the sum of squares of its arguments (Euclidean distance).

Math.cbrt(x: f64): f64

Returns the cube root of a number.

Math.imul(a: f64, b: f64): f64

Returns the result of 32-bit integer multiplication.

Math.fround(x: f64): f32

Returns the nearest 32-bit float representation of a number.

Math.clz32(x: f64): f64

Returns the number of leading zero bits in a 32-bit integer.


Example Programs

Example 1: Interactive Circle Following Cursor

import { fill, circle, reset, rect } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import * as input from "codetoy/input"

export function update(): void {
  fill(200, 200, 200)
  rect(0, 0, screen.width(), screen.height())  // Clear background
  
  fill(0, 150, 255)
  circle(input.mouseX(), input.mouseY(), 30)  // Blue circle follows mouse
}

export function onMouseDown(button: i32): void {
  if (button == 0) {
    console.log("Clicked at " + input.mouseX().toString() + ", " + input.mouseY().toString())
  }
}

Example 2: Animated Bouncing Rectangle

import { fill, rect, reset } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import { deltaTime } from "codetoy/time"

var x: f64 = 0
var speed: f64 = 150  // pixels per second

export function update(): void {
  // Clear background
  fill(50, 50, 50)
  rect(0, 0, screen.width(), screen.height())
  
  // Bounce rectangle
  x += speed * deltaTime()
  if (x + 100 > screen.width() || x < 0) {
    speed = -speed
  }
  
  fill(100, 200, 255)
  rect(x, screen.height() / 2 - 50, 100, 100)
}

Example 3: Responsive Grid

import { fill, rect, reset } from "codetoy/canvas"
import * as screen from "codetoy/screen"

const cols = 5
const rows = 4

export function update(): void {
  fill(30, 30, 30)
  rect(0, 0, screen.width(), screen.height())  // Background
  
  const cellWidth = screen.width() / cols as f64
  const cellHeight = screen.height() / rows as f64
  
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      fill(100 + col * 30, 100 + row * 30, 200)
      rect(col * cellWidth, row * cellHeight, cellWidth, cellHeight, 5)
    }
  }
}

Example 4: Drawing with Mouse

import { fill, circle, rect } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import * as input from "codetoy/input"

export function update(): void {
  fill(40, 40, 40)
  rect(0, 0, screen.width(), screen.height())  // Clear background
  
  // Draw all recorded points
  fill(255, 100, 100)
  circle(input.mouseX(), input.mouseY(), 10)
}

Example 5: Text and Fonts

import { fill, rect, text, font } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import { elapsedTime } from "codetoy/time"

export function update(): void {
  fill(30, 30, 40)
  rect(0, 0, screen.width(), screen.height())
  
  // Draw title
  fill(255, 255, 255)
  font("Arial", 32, "bold")
  text("Codetoy Playground", screen.centerX() - 150, 50)
  
  // Draw FPS counter
  font("Courier", 14)
  text("FPS: " + Math.floor(screen.fps()).toString(), 10, screen.height() - 10)
  
  // Draw frame count
  text("Frame: " + screen.frameCount().toString(), 10, screen.height() - 30)
  
  // Draw elapsed time
  const elapsed = Math.floor(elapsedTime() * 100) / 100
  text("Time: " + elapsed.toString() + "s", 10, screen.height() - 50)
}

Example 6: Pulsing Ellipses

import { fill, ellipse, rect } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import { elapsedTime } from "codetoy/time"

export function update(): void {
  fill(20, 20, 30)
  rect(0, 0, screen.width(), screen.height())  // Background
  
  const time = elapsedTime()
  
  for (let i = 1; i <= 5; i++) {
    const delay = i as f64 * 0.2
    const scale = 1.0 + Math.sin(time * 3.0 - delay) * 0.5
    
    fill(100 + i * 30, 150, 200)
    ellipse(screen.width() / 2, screen.height() / 2, 40 * scale, 20 * scale)
  }
}

Example 7: Rotating Shape

import { fill, rect, circle } from "codetoy/canvas"
import * as screen from "codetoy/screen"
import { elapsedTime } from "codetoy/time"

export function update(): void {
  fill(25, 25, 35)
  rect(0, 0, screen.width(), screen.height())  // Background
  
  const time = elapsedTime()
  const angle = time * 2.0  // Radians per second
  
  const centerX = screen.width() / 2
  const centerY = screen.height() / 2
  const radius = 80
  
  // Calculate rotated position using trigonometry
  const x = centerX + Math.cos(angle) * radius
  const y = centerY + Math.sin(angle) * radius
  
  fill(255, 150, 100)
  circle(x, y, 20)  // Rotating circle
}

Example 7: Shapes and Polygons

import { fill, triangle, polygon, circle, rect } from "codetoy/canvas"
import * as screen from "codetoy/screen"

export function update(): void {
  fill(20, 20, 30)
  rect(0, 0, screen.width(), screen.height())

  // Draw triangle
  fill(255, 100, 100)
  triangle(
    screen.centerX() - 150, 100,
    screen.centerX() - 250, 200,
    screen.centerX() - 50, 200
  )

  // Draw polygon (pentagon)
  fill(100, 200, 150)
  const pentagon = new Array<f64>()
  for (let i = 0; i < 5; i++) {
    const angle = (i as f64 / 5.0) * 2.0 * Math.PI
    pentagon.push(screen.centerX() + Math.cos(angle) * 60)
    pentagon.push(screen.centerY() + Math.sin(angle) * 60)
  }
  polygon(pentagon)

  // Draw circle
  fill(150, 100, 255)
  circle(screen.centerX() + 150, screen.centerY(), 50)
}