p5

    A port of p5.js 2.x to MoonBit (JS backend): 2D canvas and WEBGL, fonts, SVG, GIF, shaders; pixel-identical with p5.js on its parity suite.

    p5
    p5.js
    creative-coding
    canvas
    graphics
    webgl
    Download zip
    Author
    Version
    0.3.0
    License
    LGPL-2.1
    Last updated
    14 hours ago
    Downloads
    40

    No dependencies

    #p5.mbt

    MoonBit

    A port of p5.js to MoonBit, running on MoonBit's JavaScript backend and drawing on an HTML canvas.

    It covers p5.js 2.x in 2D and WEBGL: the setup/draw lifecycle, shapes and custom shapes, color (including p5 2.x's color spaces), transforms, typography with font glyph data (text_to_points), images, pixels and shader filters, SVG import/export, GIFs, media, events, math, DOM helpers and data loading; and in WEBGL, 3D primitives, cameras, lights and materials, textures, custom shaders, framebuffers, build_geometry, OBJ/STL models, text and orbit_control.

    The port follows the p5.js sources closely and is checked against p5.js itself: 55 parity cases are drawn by both and compare pixel-identical (2D and WebGL). random()/noise() give the same numbers for the same seed, font outlines match p5's Typr.js byte for byte, and the WebGL renderer uses p5's own GLSL with the same geometry, uniforms and tessellation (a port of libtess).

    fn main {
    @p5.run(
    setup=p => p.create_canvas(400, 400),
    draw=p => {
    p.background(220)
    p.fill((237, 34, 93))
    p.circle(p.mouse_x, p.mouse_y, 50)
    },
    )
    }

    #Getting started

    1. Add the module and import it in your main package:

      // moon.pkg import { "bobzhang/p5", } supported_targets = "js" options( "is-main": true, )

    2. Build for JavaScript:

      moon build --target js --release

    3. Load the generated script from a page:

      <main></main> <script src="_build/js/release/build/<your-package>/<name>.js"></script>

    #Running the examples

    moon build --target js --release python3 -m http.server 8765

    Then open http://localhost:8765/examples/. The examples are:

    ExampleShows
    shapesprimitives, Bézier/spline curves, contours, HSB colors, transforms, text, mouse
    imagesload_image in preload, filters, tint, per-pixel edits, graphics buffers
    flowfieldvectors, Perlin noise, sliders and buttons
    inputkeyboard, mouse, wheel, clip, erase
    dataload_json, load_strings, CSV tables, XML
    domvideo as pixels, radio buttons, file input, dropping files

    More elaborate demos — WEBGL scenes, shaders, flocking, two short films — live in the p5_demos module of this repository (published as bobzhang/p5_demos). The repository is a moon.work workspace, so the same build compiles both; open http://localhost:8765/p5_demos/ for the gallery.

    #Recording a sketch to video

    p.record(frames=…) renders a sketch offline: draw runs as fast as possible with delta_time and millis() advancing as if it ran at exactly 60 fps, and each frame is uploaded as a PNG. tools/record.py serves the repository and pipes the frames into ffmpeg:

    moon build --target js --release python3 tools/record.py --out history.mp4

    Then open http://localhost:8766/p5_demos/history/?record (or p5_demos/asia/?record). The films' pages also accept ?t=SECONDS&still to inspect a single moment.

    #From p5.js to MoonBit

    p5.js runs sketches in "global mode"; p5.mbt uses the equivalent of p5's instance mode: every callback receives the sketch p : @p5.P5, and all p5 functions are methods on it.

    p5.jsp5.mbt
    function setup() {…} / function draw() {…}@p5.run(setup=p => …, draw=p => …)
    function mousePressed() {…} (and other event functions)@p5.run(mouse_pressed=p => …)
    createCanvas(w, h)p.create_canvas(w, h)
    width, mouseX, frameCount, keyp.width, p.mouse_x, p.frame_count, p.key
    fill(200), fill(255, 0, 0), fill(0, 0, 255, 128), fill('red')p.fill(200), p.fill((255, 0, 0)), p.fill((0, 0, 255, 128)), p.fill("red")
    ellipse(x, y, w, h)p.ellipse(x, y, w, h=h) (h defaults to w)
    rect(x, y, w, h, r)p.rect(x, y, w, h, tl=r)
    arc(x, y, w, h, a, b, PIE)p.arc(x, y, w, h, a, b, mode=Pie)
    endShape(CLOSE)p.end_shape(mode=Close)
    random(), random(10), random(5, 10), random(arr)p.random(), p.random_max(10), p.random_range(5, 10), p.random_choice(arr)
    noise(x, y)p.noise(x, y=y)
    textAlign(CENTER, CENTER)p.text_align(HCenter, vertical=VCenter)
    colorMode(HSB, 1)p.color_mode_max(HSB, 1)
    loop()p.loop_() (loop is a MoonBit keyword)
    createVector(x, y)p.create_vector(x, y) or @p5.Vector(x, y)
    v.add(w).mult(2)v.add(w); v.mult(2) (mutating methods return Unit), or (v + w).scaled(2)
    bezierVertex(x2, y2, x3, y3, x4, y4) (p5 1.x)p.bezier_vertex3(x2, y2, x3, y3, x4, y4); p5 2.x style p.bezier_vertex(x, y) per point
    loadImage(url) in preload/async setupp.load_image(url) in preload (setup waits for it)

    Naming: camelCase becomes snake_case. Overloads become optional labeled arguments (ellipse(…, h=…)), separate functions (random_max, random_range), or the ColorArg trait for colors, which accepts numbers, 2/3/4-tuples of numbers (Int and Double can be mixed), CSS strings, Array[Double] and Color. Constants are enum constructors (Center, Pie, Close, HSB, Degrees, Square, …).

    #Packages

    PackageContentsTargets
    bobzhang/p5the sketch API (P5, run, Image, Element, …)js
    bobzhang/p5/mathVector, Noise, Random (p5's LCG), Matrix2D, map/lerp/…all
    bobzhang/p5/colorColor: RGB/HSB/HSL/HWB/Lab/LCH/OKLab/OKLCH/Display P3, CSS parsing, lerp, WCAG and APCA contrastall
    bobzhang/p5/a11yaccessible outputs: color names, text and grid descriptions of a drawingall
    bobzhang/p5/shapethe p5 2.x shape model and its conversion to canvas path commandsall
    bobzhang/p5/filtersCPU image filters (threshold, gray, invert, posterize, erode, dilate, blur)all
    bobzhang/p5/fontfont files (TrueType, CFF/OpenType, WOFF via a DEFLATE decoder), glyph outlines, kerning, arc-length sampling (ports of Typr.js and bezier-path)all
    bobzhang/p5/gifGIF encoding (gifenc) and decoding (omggif)all
    bobzhang/p5/ioCSV, Table, XMLall
    bobzhang/p5/webglthe WEBGL renderer: geometry, primitives, camera, shaders, lights, image-based lighting, texture maps, framebuffers, clipping, OBJ/MTL/STL, libtess, textjs
    bobzhang/p5/gla thin WebGL bindingjs
    bobzhang/p5/domJavaScript FFI bindings (canvas, events, images, DOM)js

    The sketch draws through the Surface trait. CanvasSurface paints on an HTML canvas; Recorder logs every drawing call, so sketches can run headless:

    let rec = @p5.Recorder::new()
    let p = @p5.P5::headless(rec, 100, 100)
    p.fill("red")
    p.rect(10, 10, 20, 20)
    rec.take() // ["…", "fill #ff0000 R10,10,20,20", "stroke #000000 w=1 …"]

    #What is ported

    • Structure: run with preload/setup/draw, frame-rate throttling as in p5's _draw, no_loop/loop_/redraw, push/pop, clip/ begin_clip/end_clip (with invert).
    • Shapes: point, line, rect/square (with rounded corners), ellipse/circle, arc (Open/Chord/Pie), triangle, quad, bezier, spline/curve; begin_shape (Path, Points, Lines, Triangles, Quads, TriangleFan, TriangleStrip, QuadStrip), vertex, bezier_vertex (order 2 or 3), spline_vertex with ends/tightness, contours; rect_mode, ellipse_mode, stroke weight/cap/join, bezier_point/bezier_tangent/spline_point/spline_tangent.
    • Color: color, fill, stroke, background, clear, erase, blend_mode, color_mode with custom maxes (RGB, HSB, HSL, HWB, LAB, LCH, OKLAB, OKLCH, and Display P3 with RGBP3 on a P2DP3 canvas), lerp_color, palette_lerp, red/green/blue/alpha/hue/ saturation/brightness/lightness, Color::contrast (WCAG 2.1 and APCA).
    • Transform: translate, rotate, scale, shear_x/shear_y, apply_matrix, reset_matrix, angle_mode.
    • Typography: text (multi-line, wrapped in a box, truncated), text_size, text_leading, text_font, load_font, text_style, text_weight, text_align, text_wrap, text_width, font_width, text_bounds, font_bounds, text_ascent, text_descent, text_property/text_properties (letter and word spacing, kerning, …); with a loaded font: Font::text_to_points, text_to_contours, text_to_paths, text_to_model (3D, optionally extruded).
    • WEBGL (create_canvas(w, h, renderer=WebGL)): box, sphere, ellipsoid, cylinder, cone, torus, plane, 2D primitives and custom shapes in 3D (vertex(x, y, z=…, u=…, v=…), normal); 3D transforms; camera, perspective, ortho, frustum, create_camera, set_camera, orbit_control; ambient_light, directional_light, point_light, spot_light, lights, light_falloff, normal_material, ambient_material, emissive_material, specular_material, shininess, metalness; image_light and panorama; texture maps (normal_texture, bump_texture, specular_texture, ambient_texture, shininess_texture); texture, texture_mode, texture_wrap, texture_interpolation, image, tint; create_shader, load_shader, shader, set_uniform, base_material_shader().modify(…) with GLSL hooks and declarations, create_filter_shader/filter_shader (also on 2D canvases); create_framebuffer (begin/end/draw, antialiasing, use as a texture); filter with p5's shader filters; clipping (begin_clip, end_clip); instances (GPU instancing); vertex_property (custom attributes); stroke_mode; debug_mode; roll; set_attributes; build_geometry, load_model (OBJ with MTL materials and texture maps, STL), model; Geometry tools (compute_tangents, calculate_bounding_box, average_normals, save_obj, save_stl, …); text with a loaded font; load_pixels/get.
    • Image: load_image, create_image, image/image_region (with Contain/Cover fitting), image_mode, tint, pixels/load_pixels/update_pixels, get/set, filter (p5's WebGL shader filters by default, CPU with use_webgl=false), copy, blend, create_graphics, save_canvas, animated GIFs (load_image, playback control, save_gif), Image resize/copy/copy_from/mask/filter/save.
    • SVG: load_svg/create_svg and shape(), build_shape, create_shape with begin/end, get_svg/save_svg.
    • Media: create_video, create_audio, create_capture; Web Audio routing with connect/disconnect.
    • Accessibility: describe, describe_element, text_output and grid_output (as fallback content or visible labels).
    • Events: mouse/pointer (mouse_x, pmouse_x, mouse_button, moved_x, touches, pressed/released/clicked/double-clicked/moved/ dragged/wheel, touch callbacks), keyboard (key, code, key_code, key_is_down, pressed/released/typed), window_resized.
    • Recording: record for frame-exact offline rendering to video.
    • Environment: frame_rate, delta_time, millis, cursor, no_cursor, fullscreen, pixel_density, display_density, window_width/window_height, resize_canvas, no_canvas, focused, get_url/get_url_path/get_url_params, webgl_version, renderer_type, drawing_context.
    • Math: Vector (all p5.Vector 2D/3D operations, slerp, reflect, angle_between, …), noise/noise_detail/noise_seed, random*, random_seed, random_gaussian, map, constrain, lerp, dist, mag, norm, sq, fract, round, trigonometry in the current angle mode.
    • Utilities and data: nf/nfc/nfp/nfs, split_tokens, shuffle, hex/unhex/binary/unbinary, year…second, local storage (store_item/get_item), load_strings/load_text/load_json, save_strings/save_json.
    • DOM: create_div/p/span/a/img/button/slider/checkbox/ select/input/color_picker, select, and Element methods for values, styling, positioning and callbacks.

    #Not ported

    • p5.strands (shaders written as JavaScript functions, and the build*Shader/load*Shader functions built on it): it works by reading JavaScript source, which has no MoonBit equivalent. Write GLSL hooks with Shader::modify instead; the built-in filters and panorama use the GLSL strands generates.
    • WebGPU, compute shaders and storage buffers (beta in p5.js 2.4).
    • JavaScript-specific helpers that MoonBit has natively: int, float, str, byte, char, abs, floor, ceil, min; the Friendly Error System, registerAddon, translations and the loading animation.
    • Variable-font axes and WOFF2 fonts. Colors in spaces other than RGB and Display P3 serialize as CSS rgb() rather than color.js's formats.

    Some names differ because of MoonBit keywords or conventions: loop_, Camera::move_by, File::file_type, texture_interpolation (p5.Texture's setInterpolation), and == / to_string for Vector.equals and toString.

    #Development

    moon check moon test # runs on the JS backend (Node), using the Recorder surface moon fmt moon info # regenerates pkg.generated.mbti

    Reference values in the math tests come from running the original p5.js sources under Node. The font package is also compared with Typr.js and bezier-path under Node (parity/font/), and the libtess port with libtess.js; the browser parity page compares whole sketches with p5.js (see parity/README.md).

    #License

    p5.js is licensed under the GNU Lesser General Public License v2.1, and this port is distributed under the same license; see LICENSE.

    ArcMode

    How arc() is closed. Without a mode, an arc is filled like a pie slice but its outline is left open.

    Camera

    using @bobzhang/p5/webgl { type Camera }

    A camera created with create_camera.

    CloseMode

    Whether end_shape / end_contour closes the path.

    Color

    using @bobzhang/p5/color { type Color }

    A color, stored in the space it was created in.

    ColorMode

    The color spaces understood by color_mode().

    Column

    using @bobzhang/p5/io { type Column }

    A column, by index or by title.

    Framebuffer

    An offscreen WEBGL surface (p5.Framebuffer).

    Geometry

    A mesh (p5.Geometry).

    Matrix2D

    A 2D affine transformation, using the same layout as the canvas setTransform(a, b, c, d, e, f):

    | a c e | | b d f | | 0 0 1 |

    Noise

    using @bobzhang/p5/math { type Noise }

    Perlin noise generator compatible with p5's noise(), noiseDetail() and noiseSeed().

    Random

    using @bobzhang/p5/math { type Random }

    A seedable pseudo random number generator, compatible with p5.js randomSeed() / random() / randomGaussian().

    Shader

    using @bobzhang/p5/webgl { type Shader }

    A shader program (p5.Shader).

    Shape

    using @bobzhang/p5/shape { type Shape }

    A shape under construction, built with begin_shape / vertex / end_shape like p5's p5.Shape.

    ShapeKind

    Kinds of shapes accepted by begin_shape() / begin_contour().

    ShapeMode

    rectMode() / ellipseMode() / imageMode() values.

    SplineEnds

    How the ends of a spline are treated (splineProperty('ends', ...)).

    Table

    using @bobzhang/p5/io { type Table }

    A table of rows and titled columns (p5.Table).

    TableRow

    using @bobzhang/p5/io { type TableRow }

    A row of a Table.

    Vector

    using @bobzhang/p5/math { type Vector }

    A 2D or 3D Euclidean vector.

    Vectors created by a sketch (create_vector) follow the sketch's angle mode in heading, rotate and angle_between, like p5.js; other vectors always use radians.

    Xml

    using @bobzhang/p5/io { type Xml }

    An XML element (p5.XML).

    XmlNode

    using @bobzhang/p5/io { type XmlNode }

    A node in an XML tree.

    ColorArg

    pub(open) trait ColorArg {
    fn to_color(Self, P5) ->
    Color

    }

    Values accepted wherever p5.js accepts color arguments: a gray level (Int/Double), a (gray, alpha) pair, a 3- or 4-tuple of channels, a CSS string or a Color. Numbers are interpreted with the current color_mode() and its maxes.

    p.fill(200) // gray
    p.fill((255, 0, 0)) // red
    p.fill((0, 0, 255, 128)) // translucent blue
    p.fill("#ff8800") // CSS
    p.fill(p.color((120, 80, 90)))
    impl ColorArg for Int
    impl ColorArg for Double
    impl ColorArg for String
    impl ColorArg for Tuple2[A, B]
    impl ColorArg for Tuple3[A, B, C]
    impl ColorArg for Tuple4[A, B, C, D]

    ImageSource

    pub(open) trait ImageSource {
    fn image_source(Self) -> (
    ImageElement
    , Int, Int, Double, Double)?
    fn advance(Self, now : Double) -> Unit = _
    fn gl_source(Self) ->
    TexSource
    ? = _
    }

    Things that can be drawn with image(): Image and graphics buffers (P5 sketches created with create_graphics).

    Num

    pub(open) trait Num {
    fn to_num(Self) -> Double
    }

    Numbers accepted inside color tuples (Int or Double).
    impl Num for Int
    impl Num for Double

    Storable

    pub(open) trait Storable {
    fn to_storage(Self) -> (String, String)
    }

    Values store_item can store, with p5's type tags so p5.js sketches on the same page can read them back.
    impl Storable for Bool
    impl Storable for Int
    impl Storable for Double
    impl Storable for String
    impl Storable for Color
    impl Storable for Vector
    impl Storable for Json

    Surface

    pub(open) trait Surface {
    fn set_transform(Self,
    Matrix2D
    ) -> Unit
    fn save(Self) -> Unit
    fn restore(Self) -> Unit
    fn fill_path(Self, Array[
    PathCmd
    ], String) -> Unit
    fn stroke_path(Self, Array[
    PathCmd
    ], String, Double, StrokeCap, StrokeJoin) -> Unit
    fn clip(Self,
    Matrix2D
    , Array[(Array[
    PathCmd
    ],
    Matrix2D
    )]) -> Unit
    fn fill_rect(Self, Double, Double, Double, Double, String) -> Unit
    fn clear_rect(Self, Double, Double, Double, Double) -> Unit
    fn set_blend_mode(Self, BlendMode) -> Unit
    fn set_text_style(Self, String, HAlign, VAlign, String) -> Unit
    fn fill_text(Self, String, Double, Double, String) -> Unit
    fn stroke_text(Self, String, Double, Double, String, Double, StrokeJoin) -> Unit
    fn measure_text(Self, String) -> TextMetrics
    fn draw_image(Self,
    ImageElement
    , Int, Int, (Double, Double, Double, Double)?, Double, Double, Double, Double, Double, Double, Double, Double) -> Unit
    fn read_pixels(Self, Int, Int, Int, Int) -> FixedArray[Byte]
    fn write_pixels(Self, FixedArray[Byte], Int, Int, Int, Int) -> Unit
    fn resize(Self, Double, Double, Double) -> Unit
    fn set_smoothing(Self, Bool) -> Unit
    fn set_css_filter(Self, String) -> Unit
    }

    A drawing backend. The sketch computes transforms and styles itself and asks the surface to paint paths, text and pixels with them.

    CanvasSurface paints on an HTML canvas; Recorder records the calls, which is handy for tests and headless use.

    AngleMode

    pub(all) enum AngleMode {
    Radians
    Degrees
    } derive(Eq,
    Debug
    )

    angleMode() values.

    BlendMode

    pub(all) enum BlendMode {
    Blend
    Remove
    Add
    Darkest
    Lightest
    Difference
    Exclusion
    Multiply
    Screen
    Replace
    Overlay
    HardLight
    SoftLight
    Dodge
    Burn
    } derive(Eq,
    Debug
    )

    blendMode() values supported by the 2D renderer.

    Bounds

    pub(all) struct Bounds {
    x : Double
    y : Double
    w : Double
    h : Double
    } derive(Eq,
    Debug
    )

    A text bounding box.

    CanvasSurface

    pub struct CanvasSurface {
    canvas :
    Canvas

    ctx :
    Context2D

    }

    A surface backed by an HTML canvas.

    CanvasSurface::new

    Wraps a canvas element.

    CanvasSurface::new_p3

    Wraps a canvas element with a Display P3 2D context.

    DebugMode

    pub(all) enum DebugMode {
    Grid
    Axes
    GridAndAxes
    } derive(Eq,
    Debug
    )

    What debug_mode shows.

    DescriptionDisplay

    pub(all) enum DescriptionDisplay {
    Fallback
    Label
    } derive(Eq,
    Debug
    )

    Where an accessible description goes: only into the canvas's fallback content (read by screen readers), or also as a visible label next to the canvas (p5's FALLBACK and LABEL).

    DisplayList

    pub struct DisplayList {
    ops : Array[DrawOp]
    // private fields
    }

    Records the calls it receives as DrawOps.

    DisplayList::new

    fn DisplayList::new(density : Double, measure : &Surface, forward? : &Surface) -> DisplayList

    A display list recording a sketch with the given pixel density, measuring text with measure and optionally forwarding every call.

    DrawOp

    pub(all) enum DrawOp {
    FillPath(Array[
    PathCmd
    ], String,
    Matrix2D
    )
    StrokePath(Array[
    PathCmd
    ], String, Double, StrokeCap, StrokeJoin,
    Matrix2D
    )
    FillRect(Double, Double, Double, Double, String,
    Matrix2D
    )
    FillText(String, Double, Double, String, String, HAlign, VAlign,
    Matrix2D
    )
    StrokeText(String, Double, Double, String, Double, String, HAlign, VAlign,
    Matrix2D
    )
    DrawImage(
    ImageElement
    , Int, Int, (Double, Double, Double, Double)?, (Double, Double, Double, Double), (Double, Double, Double, Double),
    Matrix2D
    )
    Clip(
    Matrix2D
    , Array[(Array[
    PathCmd
    ],
    Matrix2D
    )])
    Save
    Restore
    SetBlend(BlendMode)
    }

    One recorded drawing operation. Matrices map the operation's coordinates to CSS pixels of the sketch.

    Element

    pub struct Element {
    elt :
    Element

    // private fields
    }

    An HTML element created by one of the create_* functions.

    Element::add_class

    fn Element::add_class(self : Element, c : String) -> Unit

    Adds a CSS class.

    Element::append_html

    fn Element::append_html(self : Element, html : String) -> Unit

    Appends to the inner HTML.

    Element::attribute

    fn Element::attribute(self : Element, name : String, value : String) -> Unit

    Sets an attribute.

    Element::center

    fn Element::center(self : Element, align? : String) -> Unit

    Centers the element in its parent: "both" (default), "horizontal" or "vertical".

    Element::changed

    fn Element::changed(self : Element, f : () -> Unit) -> Unit

    Calls f when the element's value is committed (change event).

    Element::checked

    fn Element::checked(self : Element) -> Bool

    Whether a checkbox is checked.

    Element::child

    fn Element::child(self : Element, child : Element) -> Unit

    Appends child inside this element.

    Element::class_name

    fn Element::class_name(self : Element, c : String) -> Unit

    Sets the class attribute.

    Element::color

    The color of a color picker.

    Element::disable

    fn Element::disable(self : Element) -> Unit

    Disables the element.

    Element::double_clicked

    fn Element::double_clicked(self : Element, f : () -> Unit) -> Unit

    Calls f when the element is double-clicked.

    Element::drag_leave

    fn Element::drag_leave(self : Element, f : () -> Unit) -> Unit

    Calls f when something dragged over the element leaves it.

    Element::drag_over

    fn Element::drag_over(self : Element, f : () -> Unit) -> Unit

    Calls f when something is dragged over the element.

    Element::draggable

    fn Element::draggable(self : Element, target? : Element) -> Unit

    Lets the user drag the element around (or drag target by this element).

    Element::drop

    fn Element::drop(self : Element, on_file : (File) -> Unit, on_drop? : () -> Unit) -> Unit

    Accepts files dropped on the element: on_file is called for each one (after on_drop, if given), like p5's drop().

    Element::elt

    The underlying DOM element.

    Element::enable

    fn Element::enable(self : Element) -> Unit

    Enables the element.

    Element::get_attribute

    fn Element::get_attribute(self : Element, name : String) -> String

    Reads an attribute.

    Element::get_class

    fn Element::get_class(self : Element) -> String

    The class attribute.

    Element::get_html

    fn Element::get_html(self : Element) -> String

    The inner HTML.

    Element::get_style

    fn Element::get_style(self : Element, prop : String) -> String

    Reads a computed CSS property.

    Element::has_class

    fn Element::has_class(self : Element, c : String) -> Bool

    Whether the element has a CSS class.

    Element::height

    fn Element::height(self : Element) -> Double

    Rendered height in CSS pixels.

    Element::hide

    fn Element::hide(self : Element) -> Unit

    Hides the element.

    Element::html

    fn Element::html(self : Element, html : String) -> Unit

    Sets the inner HTML.

    Element::id

    fn Element::id(self : Element, id : String) -> Unit

    Sets the element's id.

    Element::input

    fn Element::input(self : Element, f : () -> Unit) -> Unit

    Calls f whenever the element's value changes (input event).

    Element::mouse_clicked

    fn Element::mouse_clicked(self : Element, f : () -> Unit) -> Unit

    Calls f when the element is clicked.

    Element::mouse_moved

    fn Element::mouse_moved(self : Element, f : () -> Unit) -> Unit

    Calls f when the pointer moves over the element.

    Element::mouse_out

    fn Element::mouse_out(self : Element, f : () -> Unit) -> Unit

    Calls f when the pointer leaves the element.

    Element::mouse_over

    fn Element::mouse_over(self : Element, f : () -> Unit) -> Unit

    Calls f when the pointer enters the element.

    Element::mouse_pressed

    fn Element::mouse_pressed(self : Element, f : () -> Unit) -> Unit

    Calls f when the element is clicked.

    Element::mouse_released

    fn Element::mouse_released(self : Element, f : () -> Unit) -> Unit

    Calls f when a button is released over the element.

    Element::mouse_wheel

    fn Element::mouse_wheel(self : Element, f : (Double) -> Unit) -> Unit

    Calls f(delta_y) when the wheel turns over the element.

    Element::off

    fn Element::off(self : Element, event : String) -> Unit

    Stops calling the handler of a DOM event (e.g. "pointerdown").

    Element::on

    fn Element::on(self : Element, event : String, f : () -> Unit) -> Unit

    Calls f for any DOM event name (e.g. "mouseover").

    Element::option

    fn Element::option(self : Element, label : String, value? : String) -> Unit

    Adds an option to a select element.

    Element::parent

    fn Element::parent(self : Element, id : String) -> Unit

    Moves the element inside the element with the given id.

    Element::position

    fn Element::position(self : Element, x : Double, y : Double) -> Unit

    Positions the element absolutely at (x, y) on the page.

    Element::remove

    fn Element::remove(self : Element) -> Unit

    Removes the element from the page.

    Element::remove_attribute

    fn Element::remove_attribute(self : Element, name : String) -> Unit

    Removes an attribute.

    Element::remove_class

    fn Element::remove_class(self : Element, c : String) -> Unit

    Removes a CSS class.

    Element::remove_option

    fn Element::remove_option(self : Element, value : String) -> Unit

    Removes the option with value from a radio group.

    Element::selected

    fn Element::selected(self : Element, value : String) -> Unit

    Selects an option of a select element (or sets an input's value).

    Element::set_checked

    fn Element::set_checked(self : Element, v : Bool) -> Unit

    Checks or unchecks a checkbox.

    Element::set_value

    fn Element::set_value(self : Element, v : String) -> Unit

    Sets the value of an input element.

    Element::show

    fn Element::show(self : Element) -> Unit

    Shows the element.

    Element::size

    fn Element::size(self : Element, w : Double, h : Double) -> Unit

    Sets the element's CSS size in pixels.

    Element::style

    fn Element::style(self : Element, prop : String, value : String) -> Unit

    Sets a CSS property.

    Element::toggle_class

    fn Element::toggle_class(self : Element, c : String) -> Unit

    Adds or removes a CSS class.

    Element::value

    fn Element::value(self : Element) -> String

    The value of an input, slider, select or color picker, as a string.

    Element::value_number

    fn Element::value_number(self : Element) -> Double

    The value parsed as a number (0 when it isn't one).

    Element::width

    fn Element::width(self : Element) -> Double

    Rendered width in CSS pixels.

    File

    pub struct File {
    file :
    File

    file_type : String
    subtype : String
    name : String
    size : Int
    data : String
    // private fields
    }

    A file chosen in a file input or dropped on an element (p5.File).

    File::json

    Parses the contents of a JSON file.

    File::revoke

    fn File::revoke(self : File) -> Unit

    Releases the blob URL of an audio/video file.

    Filter

    pub(all) enum Filter {
    Threshold(Double)
    Gray
    Opaque
    Invert
    Posterize(Int)
    Blur(Double)
    Erode
    Dilate
    } derive(Eq,
    Debug
    )

    Filters for filter().

    Font

    pub struct Font {
    family : String
    loaded : Bool
    data :
    FontData
    ?
    // private fields
    }

    A font loaded with load_font; use it with text_font_face.

    Font::text_to_contours

    fn Font::text_to_contours(self : Font, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double, sample_factor? : Double, simplify_threshold? : Double) -> Array[Array[TextPoint]]

    Points along each contour of the outline of s (p5's font.textToContours): the letter "O" gives two arrays. sample_factor is points per pixel of path length; with simplify_threshold (radians) nearly collinear points are dropped.

    Font::text_to_model

    fn Font::text_to_model(self : Font, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double, extrude? : Double, sample_factor? : Double, simplify_threshold? : Double) ->
    Geometry

    The outline of s as a flat 3D model, or, with extrude, a solid one that thick (font.textToModel). Needs a WEBGL sketch. Points are sampled like text_to_contours.

    Font::text_to_paths

    fn Font::text_to_paths(self : Font, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double) -> Array[
    PathCmd
    ]

    The outline of s as path commands, laid out as text(s, x, y, …) would draw it with this font (p5's font.textToPaths).

    Font::text_to_points

    fn Font::text_to_points(self : Font, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double, sample_factor? : Double, simplify_threshold? : Double) -> Array[TextPoint]

    Points outlining s (p5's font.textToPoints): all contours of text_to_contours in one array.

    GlAttribute

    pub(all) enum GlAttribute {
    Alpha(Bool)
    Depth(Bool)
    Stencil(Bool)
    Antialias(Bool)
    PremultipliedAlpha(Bool)
    PreserveDrawingBuffer(Bool)
    PerPixelLighting(Bool)
    Version(Int)
    }

    A WebGL context setting for set_attributes.

    HAlign

    pub(all) enum HAlign {
    Left
    HCenter
    Right
    Start
    End
    } derive(Eq,
    Debug
    )

    Horizontal text alignment (textAlign(h, ...)).

    Image

    pub struct Image {
    width : Double
    height : Double
    pixels : FixedArray[Byte]
    // private fields
    }

    An image (loaded from a file or created with create_image), backed by an off-screen canvas. Use load_pixels / pixels / update_pixels to edit pixels.

    Image::blend_from

    fn[I : ImageSource] Image::blend_from(self : Image, src : I, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double, mode : BlendMode) -> Unit

    Combines a region of src into this image with mode.

    Image::copy

    fn Image::copy(self : Image) -> Image

    A copy of the image.

    Image::copy_from

    fn[I : ImageSource] Image::copy_from(self : Image, src : I, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unit

    Copies a region of src into a region of this image, scaling it.

    Image::delay

    fn Image::delay(self : Image, ms : Double, index? : Int) -> Unit

    Sets the delay (ms) of one frame, or of every frame when index is omitted or out of range.

    Image::filter

    fn Image::filter(self : Image, f : Filter) -> Unit

    Applies a filter to the image.

    Image::get

    fn Image::get(self : Image, x : Double, y : Double) ->
    Color

    The color of one pixel (transparent black outside the image).

    Image::get_current_frame

    fn Image::get_current_frame(self : Image) -> Int

    Index of the frame currently shown.

    Image::get_region

    fn Image::get_region(self : Image, x : Double, y : Double, w : Double, h : Double) -> Image

    A copy of a rectangular region (the whole image by default).

    Image::load_pixels

    fn Image::load_pixels(self : Image) -> Unit

    Loads the pixels of the image into pixels.

    Image::mask

    fn[I : ImageSource] Image::mask(self : Image, mask : I) -> Unit

    Uses the alpha channel of mask as this image's alpha.

    Image::num_frames

    fn Image::num_frames(self : Image) -> Int

    Number of frames of an animated GIF (1 for still images).

    Image::pause

    fn Image::pause(self : Image) -> Unit

    Pauses an animated GIF.

    Image::play

    fn Image::play(self : Image) -> Unit

    Resumes an animated GIF.

    Image::reset

    fn Image::reset(self : Image) -> Unit

    Restarts an animated GIF from its first frame.

    Image::resize

    fn Image::resize(self : Image, w : Double, h : Double) -> Unit

    Resizes the image. A size of 0 keeps the aspect ratio.

    Image::save

    fn Image::save(self : Image, filename? : String) -> Unit

    Downloads the image as a PNG.

    Image::save_as

    fn Image::save_as(self : Image, filename : String, ext? : String) -> Unit

    Saves the image as a PNG, or as an animated GIF when ext is "gif" and the image is an animated GIF.

    Image::set

    fn Image::set(self : Image, x : Double, y : Double, c :
    Color
    ) -> Unit

    Sets one pixel in pixels (loading them first if needed). Call update_pixels() to apply.

    Image::set_frame

    fn Image::set_frame(self : Image, index : Int) -> Unit

    Shows frame index of an animated GIF.

    Image::update_pixels

    fn Image::update_pixels(self : Image) -> Unit

    Writes pixels back into the image.

    ImageFit

    pub(all) enum ImageFit {
    Contain
    Cover
    } derive(Eq,
    Debug
    )

    How image() fits an image into a destination of another aspect ratio (p5's CONTAIN and COVER).

    MediaElement

    pub struct MediaElement {
    element : Element
    width : Double
    height : Double
    pixels : FixedArray[Byte]
    // private fields
    }

    A <video> or <audio> element (p5.MediaElement).

    MediaElement::add_cue

    fn MediaElement::add_cue(self : MediaElement, time : Double, callback : () -> Unit) -> Int

    Calls callback when playback passes time (seconds). Returns an id for remove_cue.

    MediaElement::autoplay

    fn MediaElement::autoplay(self : MediaElement, on : Bool) -> Unit

    Sets whether the media starts playing on its own.

    MediaElement::clear_cues

    fn MediaElement::clear_cues(self : MediaElement) -> Unit

    Removes every cue.

    MediaElement::connect

    Routes the element's audio through Web Audio into node (and the speakers); without a node, only to the speakers (connect).

    MediaElement::disconnect

    fn MediaElement::disconnect(self : MediaElement) -> Unit

    Removes the element's Web Audio routing, including to the speakers.

    MediaElement::duration

    fn MediaElement::duration(self : MediaElement) -> Double

    The length in seconds.

    MediaElement::get

    fn MediaElement::get(self : MediaElement, x : Double, y : Double) ->
    Color

    The color of the current frame at (x, y).

    MediaElement::get_speed

    fn MediaElement::get_speed(self : MediaElement) -> Double

    The playback speed.

    MediaElement::get_volume

    fn MediaElement::get_volume(self : MediaElement) -> Double

    The volume.

    MediaElement::hide

    fn MediaElement::hide(self : MediaElement) -> Unit

    Hides the element (it can still be drawn with image()).

    MediaElement::hide_controls

    fn MediaElement::hide_controls(self : MediaElement) -> Unit

    Hides the browser's playback controls.

    MediaElement::load_pixels

    fn MediaElement::load_pixels(self : MediaElement) -> Unit

    Loads the current video frame into pixels.

    MediaElement::loop_

    fn MediaElement::loop_(self : MediaElement) -> Unit

    Plays in a loop.

    MediaElement::no_loop

    fn MediaElement::no_loop(self : MediaElement) -> Unit

    Stops looping (playback continues to the end).

    MediaElement::on_ended

    fn MediaElement::on_ended(self : MediaElement, f : (MediaElement) -> Unit) -> Unit

    Calls f when playback reaches the end.

    MediaElement::pause

    fn MediaElement::pause(self : MediaElement) -> Unit

    Pauses playback.

    MediaElement::play

    fn MediaElement::play(self : MediaElement) -> Unit

    Plays from the current position (from the start when it had ended).

    MediaElement::position

    fn MediaElement::position(self : MediaElement, x : Double, y : Double) -> Unit

    Positions the element on the page.

    MediaElement::remove_cue

    fn MediaElement::remove_cue(self : MediaElement, id : Int) -> Unit

    Removes a cue added with add_cue.

    MediaElement::set_src

    fn MediaElement::set_src(self : MediaElement, src : String) -> Unit

    Replaces what the media element plays.

    MediaElement::set_time

    fn MediaElement::set_time(self : MediaElement, t : Double) -> Unit

    Jumps to a position in seconds.

    MediaElement::show

    fn MediaElement::show(self : MediaElement) -> Unit

    Shows the element.

    MediaElement::show_controls

    fn MediaElement::show_controls(self : MediaElement) -> Unit

    Shows the browser's playback controls.

    MediaElement::size

    fn MediaElement::size(self : MediaElement, w : Double, h : Double) -> Unit

    Sets the displayed size of the element (and of the frames drawn from it).

    MediaElement::speed

    fn MediaElement::speed(self : MediaElement, v : Double) -> Unit

    Sets the playback speed (1 is normal).

    MediaElement::src

    fn MediaElement::src(self : MediaElement) -> String

    The URL the media element plays (src).

    MediaElement::stop

    fn MediaElement::stop(self : MediaElement) -> Unit

    Stops playback and rewinds.

    MediaElement::time

    fn MediaElement::time(self : MediaElement) -> Double

    The current position in seconds.

    MediaElement::volume

    fn MediaElement::volume(self : MediaElement, v : Double) -> Unit

    Sets the volume (0 to 1).

    MouseButtons

    pub(all) struct MouseButtons {
    left : Bool
    center : Bool
    right : Bool
    } derive(Eq,
    Debug
    )

    Which mouse buttons are currently held down.
    pub struct P5 {
    width : Double
    height : Double
    frame_count : Int
    delta_time : Double
    mouse_x : Double
    mouse_y : Double
    pmouse_x : Double
    pmouse_y : Double
    win_mouse_x : Double
    win_mouse_y : Double
    pwin_mouse_x : Double
    pwin_mouse_y : Double
    moved_x : Double
    moved_y : Double
    mouse_button : MouseButtons
    mouse_is_pressed : Bool
    key : String
    code : String
    key_code : Int
    key_is_pressed : Bool
    touches : Array[Touch]
    focused : Bool
    window_width : Double
    window_height : Double
    acceleration_x : Double
    acceleration_y : Double
    acceleration_z : Double
    p_acceleration_x : Double
    p_acceleration_y : Double
    p_acceleration_z : Double
    rotation_x : Double
    rotation_y : Double
    rotation_z : Double
    p_rotation_x : Double
    p_rotation_y : Double
    p_rotation_z : Double
    turn_axis : String
    device_orientation : String
    pixels : FixedArray[Byte]
    // private fields
    }

    A p5 sketch (or an off-screen graphics buffer created with create_graphics). All drawing functions are methods of this type.
    impl ImageSource for P5

    P5::acos

    fn P5::acos(self : P5, v : Double) -> Double

    Arc cosine, in the current angle mode.

    P5::alpha

    fn[C : ColorArg] P5::alpha(self : P5, c : C) -> Double

    Alpha of a color, in the current mode's alpha range.

    P5::ambient_light

    fn[C : ColorArg] P5::ambient_light(self : P5, c : C) -> Unit

    Adds ambient light.

    P5::ambient_material

    fn[C : ColorArg] P5::ambient_material(self : P5, c : C) -> Unit

    The color reflected from ambient light (also turns lighting on).

    P5::ambient_texture

    fn[I : ImageSource] P5::ambient_texture(self : P5, img : I?) -> Unit

    Uses an image as the ambient color across the surface (ambientTexture). None clears.

    P5::angle_mode

    fn P5::angle_mode(self : P5, mode : AngleMode) -> Unit

    Sets the angle unit used by rotate, arc, sin, atan2, etc.

    P5::apply_matrix

    fn P5::apply_matrix(self : P5, a : Double, b : Double, c : Double, d : Double, e : Double, f : Double) -> Unit

    Multiplies the current matrix by [a c e; b d f; 0 0 1].

    P5::apply_matrix4

    fn P5::apply_matrix4(self : P5, m : ArrayView[Double]) -> Unit

    Applies a 4x4 matrix given as 16 column-major entries (WEBGL).

    P5::arc

    fn P5::arc(self : P5, x : Double, y : Double, w : Double, h : Double, start : Double, stop : Double, mode? :
    ArcMode
    ) -> Unit

    Draws an arc of the ellipse x, y, w, h from start to stop (in the current angle mode), clockwise.

    P5::asin

    fn P5::asin(self : P5, v : Double) -> Double

    Arc sine, in the current angle mode.

    P5::atan

    fn P5::atan(self : P5, v : Double) -> Double

    Arc tangent, in the current angle mode.

    P5::atan2

    fn P5::atan2(self : P5, y : Double, x : Double) -> Double

    Angle of the point (x, y) from the positive x-axis, in the current angle mode.

    P5::background

    fn[C : ColorArg] P5::background(self : P5, c : C) -> Unit

    Fills the whole canvas with a color (ignores the current transform).

    P5::base_color_shader

    fn P5::base_color_shader(self : P5) ->
    Shader
    ?

    p5's flat color shader, for modify.

    P5::base_material_shader

    fn P5::base_material_shader(self : P5) ->
    Shader
    ?

    p5's material shader (with lights), for modify.

    P5::base_normal_shader

    fn P5::base_normal_shader(self : P5) ->
    Shader
    ?

    p5's normal-colored shader, for modify.

    P5::base_stroke_shader

    fn P5::base_stroke_shader(self : P5) ->
    Shader
    ?

    p5's stroke shader, for modify.

    P5::begin_clip

    fn P5::begin_clip(self : P5, invert? : Bool) -> Unit

    Starts defining a clipping mask: shapes drawn until end_clip() are not painted but form the mask. With invert=true the mask is inverted. The clip lasts until the matching pop() (or the end of the frame).

    P5::begin_contour

    fn P5::begin_contour(self : P5, kind? :
    ShapeKind
    ) -> Unit

    Starts a contour (e.g. a hole) inside the current shape.

    P5::begin_shape

    fn P5::begin_shape(self : P5, kind? :
    ShapeKind
    ) -> Unit

    Starts recording vertices for a custom shape.

    P5::bezier

    fn P5::bezier(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double, x4 : Double, y4 : Double) -> Unit

    Draws a cubic Bézier curve from (x1, y1) to (x4, y4) with control points (x2, y2) and (x3, y3).

    P5::bezier_order

    fn P5::bezier_order(self : P5, order : Int) -> Unit

    Sets the order of Bézier curves built with bezier_vertex (2 or 3).

    P5::bezier_vertex

    fn P5::bezier_vertex(self : P5, x : Double, y : Double, z? : Double, u? : Double, v? : Double) -> Unit

    Adds a Bézier vertex. The first one in a path is the anchor; then every bezier_order() vertices (3 by default) form one curve.

    P5::bezier_vertex3

    fn P5::bezier_vertex3(self : P5, cx1 : Double, cy1 : Double, cx2 : Double, cy2 : Double, x : Double, y : Double) -> Unit

    p5.js 1.x style bezierVertex(cx1, cy1, cx2, cy2, x, y).

    P5::blend

    fn[I : ImageSource] P5::blend(self : P5, src : I, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double, mode : BlendMode) -> Unit

    Copies a region like copy, combining pixels with mode, like p5's blend().

    P5::blend_mode

    fn P5::blend_mode(self : P5, mode : BlendMode) -> Unit

    Sets how new pixels are combined with existing ones.

    P5::blue

    fn[C : ColorArg] P5::blue(self : P5, c : C) -> Double

    Blue component of a color, in the current RGB range.

    P5::box

    fn P5::box(self : P5, w? : Double, h? : Double, d? : Double, detail_x? : Int, detail_y? : Int) -> Unit

    A box of w × h × d (default 50; h defaults to w, d to h).

    P5::brightness

    fn[C : ColorArg] P5::brightness(self : P5, c : C) -> Double

    HSB brightness of a color.

    P5::build_geometry

    fn P5::build_geometry(self : P5, f : () -> Unit) ->
    Geometry
    ?

    Draws with f into a new geometry instead of the canvas (buildGeometry): shapes and models drawn inside are merged, with transforms applied. Vertices keep the fill set inside f; others use the material color when the geometry is drawn.

    P5::build_shape

    fn P5::build_shape(self : P5, body : () -> Unit, draw? : Bool) -> ShapeCollection

    Records the drawing done in body into a shape collection, like p5's buildShape(). With draw, it is also drawn on the canvas.

    P5::bump_texture

    fn[I : ImageSource] P5::bump_texture(self : P5, img : I?, scale? : Double) -> Unit

    Tilts the surface normals using an image's brightness as height (bumpTexture). None clears.

    P5::camera

    fn P5::camera(self : P5, eye? : (Double, Double, Double), center? : (Double, Double, Double), up? : (Double, Double, Double)) -> Unit

    Positions the camera: eye, center (look-at point) and up vector. With no arguments, the default camera.

    P5::canvas

    fn P5::canvas(self : P5) ->
    Canvas
    ?

    The underlying canvas element, when the sketch draws on one.

    P5::canvas_element

    fn P5::canvas_element(self : P5) -> Element?

    The sketch's canvas as an element (to position it, accept dropped files, etc.).

    P5::circle

    fn P5::circle(self : P5, x : Double, y : Double, d : Double) -> Unit

    Draws a circle of diameter d.

    P5::clear

    fn P5::clear(self : P5) -> Unit

    Makes every pixel of the canvas transparent.

    P5::clear_depth

    fn P5::clear_depth(self : P5, depth? : Double) -> Unit

    Clears the depth buffer, so what is drawn next is not hidden by earlier 3D shapes (clearDepth).

    P5::clip

    fn P5::clip(self : P5, mask : () -> Unit, invert? : Bool) -> Unit

    Draws the shapes of mask as a clipping mask, like p5's clip().

    P5::color

    fn[C : ColorArg] P5::color(self : P5, c : C) ->
    Color

    Creates a color using the current color mode, like p5's color().

    P5::color_mode

    fn P5::color_mode(self : P5, mode :
    ColorMode
    ) -> Unit

    Sets how color numbers are interpreted (colorMode(mode)).

    P5::color_mode_max

    fn P5::color_mode_max(self : P5, mode :
    ColorMode
    , max : Double) -> Unit

    Sets the color mode and the maximum of every channel, like colorMode(mode, max).

    P5::color_mode_maxes

    fn P5::color_mode_maxes(self : P5, mode :
    ColorMode
    , max1 : Double, max2 : Double, max3 : Double, max_alpha? : Double) -> Unit

    Sets the color mode and per-channel maxima, like colorMode(mode, max1, max2, max3, maxA).

    P5::cone

    fn P5::cone(self : P5, r? : Double, h? : Double, detail_x? : Int, detail_y? : Int, cap? : Bool) -> Unit

    A cone of base radius r and height h (defaults 50 and r).

    P5::copy

    fn[I : ImageSource] P5::copy(self : P5, src : I, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unit

    Copies a region of src (an image, a graphics buffer, or the sketch itself) into a region of the canvas, scaling it, like p5's copy().

    P5::cos

    fn P5::cos(self : P5, angle : Double) -> Double

    Cosine of an angle in the current angle mode.

    P5::create_a

    fn P5::create_a(self : P5, href : String, html : String, target? : String) -> Element

    Creates a link.

    P5::create_audio

    fn P5::create_audio(self : P5, sources : Array[String], on_load? : (MediaElement) -> Unit) -> MediaElement

    Creates an <audio> element from one or more source URLs.

    P5::create_button

    fn P5::create_button(self : P5, label : String) -> Element

    Creates a button.

    P5::create_camera

    fn P5::create_camera(self : P5) ->
    Camera
    ?

    A new camera with the default settings.

    P5::create_canvas

    fn P5::create_canvas(self : P5, w : Double, h : Double, renderer? : RendererKind) -> Unit

    Resizes the canvas to w×h and resets the drawing state. Call it in setup.

    P5::create_capture

    fn P5::create_capture(self : P5, video? : Bool, audio? : Bool, flipped? : Bool, on_ready? : (MediaElement) -> Unit) -> MediaElement

    Captures the webcam (and/or microphone) in a <video>, like p5's createCapture(). The browser asks the user for permission. With flipped, the image is mirrored.

    P5::create_checkbox

    fn P5::create_checkbox(self : P5, label? : String, checked? : Bool) -> Element

    Creates a checkbox with a label.

    P5::create_color_picker

    fn P5::create_color_picker(self : P5, value? : String) -> Element

    Creates a color picker.

    P5::create_div

    fn P5::create_div(self : P5, html? : String) -> Element

    Creates a <div>.

    P5::create_element

    fn P5::create_element(self : P5, tag : String, content? : String) -> Element

    Creates an element with any tag (e.g. "h2", "ul"), with optional inner HTML.

    P5::create_file_input

    fn P5::create_file_input(self : P5, on_file : (File) -> Unit, multiple? : Bool) -> Element

    Creates a file picker; on_file is called for each chosen file.

    P5::create_filter_shader

    fn P5::create_filter_shader(self : P5, frag : String) ->
    Shader

    Creates a filter shader from a fragment shader alone (createFilterShader): it reads the canvas from tex0 at vTexCoord and also gets texelSize and canvasSize. Apply it with filter_shader.

    P5::create_framebuffer

    fn P5::create_framebuffer(self : P5, width? : Double, height? : Double, density? : Double, antialias? : Int, depth? : Bool, stencil? : Bool, depth_float? : Bool, linear? : Bool) ->
    Framebuffer
    ?

    Creates a framebuffer. Without a size it follows the canvas.

    P5::create_graphics

    fn P5::create_graphics(self : P5, w : Double, h : Double) -> P5

    Creates an off-screen graphics buffer with the same drawing API as the sketch. Draw it with image().

    P5::create_image

    fn P5::create_image(_self : P5, w : Double, h : Double) -> Image

    Creates a blank (transparent) image.

    P5::create_img

    fn P5::create_img(self : P5, src : String, alt? : String) -> Element

    Creates an <img> element.

    P5::create_input

    fn P5::create_input(self : P5, value? : String, kind? : String) -> Element

    Creates a text input (or any <input> type such as "number", "password").

    P5::create_model

    fn P5::create_model(self : P5, obj : String, normalize? : Bool) ->
    Geometry

    A model from OBJ text (createModel).

    P5::create_p

    fn P5::create_p(self : P5, html? : String) -> Element

    Creates a <p> paragraph.

    P5::create_radio

    fn P5::create_radio(self : P5, name? : String) -> Element

    Creates a group of radio buttons; add choices with option(value,label?) and read the choice with value().

    P5::create_select

    fn P5::create_select(self : P5) -> Element

    Creates a drop-down menu; add entries with option.

    P5::create_shader

    fn P5::create_shader(self : P5, vert : String, frag : String) ->
    Shader

    Creates a shader from GLSL vertex and fragment sources.

    P5::create_shape

    fn P5::create_shape(self : P5) -> ShapeCollection

    An empty shape collection to record into with begin / end (createShape).

    P5::create_slider

    fn P5::create_slider(self : P5, min : Double, max : Double, value? : Double, step? : Double) -> Element

    Creates a range slider.

    P5::create_span

    fn P5::create_span(self : P5, html? : String) -> Element

    Creates a <span>.

    P5::create_vector

    fn P5::create_vector(self : P5, x : Double, y : Double, z? : Double) ->
    Vector

    Creates a vector, like p5's createVector(x, y, z).

    P5::create_video

    fn P5::create_video(self : P5, sources : Array[String], on_load? : (MediaElement) -> Unit) -> MediaElement

    Creates a <video> from one or more source URLs (alternative formats). on_load runs when it can play through. Hide it with .element.hide() to draw it on the canvas with image() instead.

    P5::create_writer

    fn P5::create_writer(_self : P5, name : String, ext? : String) -> PrintWriter

    Creates a writer for name.ext (txt by default).

    P5::cursor

    fn P5::cursor(self : P5, kind? : String) -> Unit

    Sets the cursor shown over the canvas (any CSS cursor, e.g. "pointer", "crosshair", "grab", or "url(...)").

    P5::curve

    fn P5::curve(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double, x4 : Double, y4 : Double) -> Unit

    Alias of spline (p5.js 1.x curve()), always with excluded ends.

    P5::curve_detail

    fn P5::curve_detail(self : P5, d : Double) -> Unit

    Sets how finely curves are sampled in WEBGL (points per pixel of length, default 1/4).

    P5::curve_tightness

    fn P5::curve_tightness(self : P5, t : Double) -> Unit

    Alias of spline_tightness (p5.js 1.x curveTightness).

    P5::curve_vertex

    fn P5::curve_vertex(self : P5, x : Double, y : Double) -> Unit

    Alias of spline_vertex (p5.js 1.x curveVertex).

    P5::cylinder

    fn P5::cylinder(self : P5, r? : Double, h? : Double, detail_x? : Int, detail_y? : Int, bottom_cap? : Bool, top_cap? : Bool) -> Unit

    A cylinder of radius r and height h (defaults 50 and r).

    P5::debug_mode

    fn P5::debug_mode(self : P5, mode? : DebugMode, grid_size? : Double, grid_divisions? : Int, grid_offset? : (Double, Double, Double), axes_size? : Double, axes_offset? : (Double, Double, Double)) -> Unit

    Draws a ground grid and/or an axes icon after every frame, to help find your way in 3D. Defaults follow p5: a grid of width / 2 with a division every ~30 units, and an axes icon of max(width / 20, 40) at -width / 4 on all axes.

    P5::describe

    fn P5::describe(self : P5, text : String, display? : DescriptionDisplay, lang? : String) -> Unit

    Describes the canvas for screen readers. With display=Label the description is also shown below the canvas. lang sets its language.

    P5::describe_element

    fn P5::describe_element(self : P5, name : String, text : String, display? : DescriptionDisplay, lang? : String) -> Unit

    Describes one element of the canvas: name and text become a row of a table in the canvas's description.

    P5::directional_light

    fn[C : ColorArg] P5::directional_light(self : P5, c : C, x : Double, y : Double, z : Double) -> Unit

    Adds a directional light shining along (x, y, z).

    P5::display_density

    fn P5::display_density(_self : P5) -> Double

    The display's pixel density.

    P5::display_height

    fn P5::display_height(_self : P5) -> Double

    Height of the screen.

    P5::display_width

    fn P5::display_width(_self : P5) -> Double

    Width of the screen.

    P5::drawing_context

    fn P5::drawing_context(self : P5) ->
    Context2D
    ?

    The 2D drawing context of the canvas, for calling Canvas API features p5 doesn't wrap (drawingContext). None in WEBGL or headless.

    P5::ellipse

    fn P5::ellipse(self : P5, x : Double, y : Double, w : Double, h? : Double) -> Unit

    Draws an ellipse. Its meaning depends on ellipse_mode() (center by default). h defaults to w.

    P5::ellipse_mode

    fn P5::ellipse_mode(self : P5, mode :
    ShapeMode
    ) -> Unit

    Sets how ellipse(), circle() and arc() interpret their arguments.

    P5::ellipsoid

    fn P5::ellipsoid(self : P5, rx? : Double, ry? : Double, rz? : Double, detail_x? : Int, detail_y? : Int) -> Unit

    An ellipsoid with radii rx, ry, rz (ry and rz default to rx).

    P5::emissive_material

    fn[C : ColorArg] P5::emissive_material(self : P5, c : C) -> Unit

    A color the surface emits regardless of lights.

    P5::end_clip

    fn P5::end_clip(self : P5) -> Unit

    Finishes the clipping mask started by begin_clip().

    P5::end_contour

    fn P5::end_contour(self : P5, mode? :
    CloseMode
    ) -> Unit

    Ends the current contour; Close connects it back to its first vertex.

    P5::end_shape

    fn P5::end_shape(self : P5, mode? :
    CloseMode
    , count? : Int) -> Unit

    Finishes the current shape and draws it. In WEBGL, count draws that many instances (see instances).

    P5::erase

    fn P5::erase(self : P5, strength_fill? : Double, strength_stroke? : Double) -> Unit

    Starts erasing: subsequent shapes remove pixels instead of painting. strength_fill / strength_stroke (0-255) control how much is erased.

    P5::exit_pointer_lock

    fn P5::exit_pointer_lock(_self : P5) -> Unit

    Releases a pointer lock.

    P5::fill

    fn[C : ColorArg] P5::fill(self : P5, c : C) -> Unit

    Sets the fill color.

    P5::filter

    fn P5::filter(self : P5, f : Filter, use_webgl? : Bool) -> Unit

    Applies a filter to the whole canvas, on the CPU (like p5's filter(type, param, false)).

    P5::filter_shader

    fn P5::filter_shader(self : P5, s :
    Shader
    ) -> Unit

    Runs a filter shader over the canvas (filter(shader)), in 2D or WEBGL.

    P5::font_ascent

    fn P5::font_ascent(self : P5) -> Double

    Ascent of the current font.

    P5::font_bounds

    fn P5::font_bounds(self : P5, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double) -> Bounds

    The loose bounding box of text, from the font's ascent and descent and the advance width.

    P5::font_descent

    fn P5::font_descent(self : P5) -> Double

    Descent of the current font.

    P5::font_width

    fn P5::font_width(self : P5, s : String) -> Double

    Advance width of a string (the widest line), like p5 2.x fontWidth().

    P5::frame_rate

    fn P5::frame_rate(self : P5, fps : Double) -> Unit

    Sets the target frame rate (frames per second).

    P5::free_geometry

    fn P5::free_geometry(self : P5, g :
    Geometry
    ) -> Unit

    Frees the GPU buffers of a geometry.

    P5::frustum

    fn P5::frustum(self : P5, left? : Double, right? : Double, bottom? : Double, top? : Double, near? : Double, far? : Double) -> Unit

    Sets a frustum projection.

    P5::fullscreen

    fn P5::fullscreen(self : P5, on : Bool) -> Unit

    Enters or leaves full-screen mode (must be triggered by a user gesture).

    P5::get

    fn P5::get(self : P5, x : Double, y : Double) ->
    Color

    The color of the canvas at (x, y).

    P5::get_angle_mode

    fn P5::get_angle_mode(self : P5) -> AngleMode

    The current angle mode.

    P5::get_color_mode

    fn P5::get_color_mode(self : P5) ->
    ColorMode

    The current color mode.

    P5::get_fill

    fn P5::get_fill(self : P5) ->
    Color
    ?

    The current fill color, if any.

    P5::get_frame_rate

    fn P5::get_frame_rate(self : P5) -> Double

    The measured frame rate of the last frame.

    P5::get_matrix

    fn P5::get_matrix(self : P5) ->
    Matrix2D

    The current transform (user space to CSS pixels).

    P5::get_pixel_density

    fn P5::get_pixel_density(self : P5) -> Double

    The current pixel density.

    P5::get_region

    fn P5::get_region(self : P5, x : Double, y : Double, w : Double, h : Double) -> Image

    Copies a region of the canvas into a new image.

    P5::get_stroke

    fn P5::get_stroke(self : P5) ->
    Color
    ?

    The current stroke color, if any.

    P5::get_stroke_mode

    fn P5::get_stroke_mode(self : P5) -> StrokeMode

    The current stroke mode.

    P5::get_svg

    fn P5::get_svg(self : P5, coll : ShapeCollection, width? : Double, height? : Double) -> String

    The collection as an SVG document of width×height (the sketch size by default), like p5's getSVG().

    P5::get_target_frame_rate

    fn P5::get_target_frame_rate(self : P5) -> Double

    The target frame rate.

    P5::get_text_leading

    fn P5::get_text_leading(self : P5) -> Double

    The current leading.

    P5::get_text_properties

    fn P5::get_text_properties(self : P5) -> Map[String, String]

    The current text properties by name, as textProperties() returns them.

    P5::get_text_property

    fn P5::get_text_property(self : P5, name : String) -> String?

    One text property by name (see text_property), or None if unknown.

    P5::get_text_size

    fn P5::get_text_size(self : P5) -> Double

    The current font size.

    P5::get_text_weight

    fn P5::get_text_weight(self : P5) -> String

    The font weight ("normal" or a number).

    P5::get_url

    fn P5::get_url(self : P5) -> String

    The page's full URL (getURL).

    P5::get_url_params

    fn P5::get_url_params(self : P5) -> Map[String, String]

    The query parameters of the URL (getURLParams): ?a=1&b=x gives {"a": "1", "b": "x"}. Like p5, parameters without a value are skipped.

    P5::get_url_path

    fn P5::get_url_path(self : P5) -> Array[String]

    The parts of the URL's path (getURLPath), e.g. ["sketches", "a"].

    P5::green

    fn[C : ColorArg] P5::green(self : P5, c : C) -> Double

    Green component of a color, in the current RGB range.

    P5::grid_output

    fn P5::grid_output(self : P5, display? : DescriptionDisplay) -> Unit

    Describes the shapes on the canvas as a 10 × 10 grid, updated every frame. With display=Label the output is also shown next to the canvas. 2D only, as in p5.

    P5::headless

    fn P5::headless(surface : &Surface, width : Double, height : Double, pixel_density? : Double, seed? : Double) -> P5

    Creates a sketch that draws into surface without a browser canvas or animation loop (useful for tests and for recording drawings). Call setup / draw callbacks yourself, or use redraw() after set_draw.

    test {
    let rec = @p5.Recorder::new()
    let p = @p5.P5::headless(rec, 50, 50)
    ignore(rec.take()) // drop the initial state setup
    p.no_stroke()
    p.fill("red")
    p.rect(10, 10, 20, 20)
    inspect(
    rec.take().join("\n"),
    content=(
    #|transform 1 0 0 1 0 0
    #|fill #ff0000 R10,10,20,20
    ),
    )
    }

    P5::http_do

    fn P5::http_do(self : P5, url : String, http_method? : String, body? : String, content_type? : String, on_response~ : (String) -> Unit, on_error? : (String) -> Unit) -> Unit

    Makes an HTTP request (http_method such as "GET", "POST", "PUT"); on_response(body) receives the response text, on_error(message) network errors and non-2xx statuses.

    P5::http_get

    fn P5::http_get(self : P5, url : String, on_response : (String) -> Unit, on_error? : (String) -> Unit) -> Unit

    GET request.

    P5::http_post

    fn P5::http_post(self : P5, url : String, body : String, on_response : (String) -> Unit, on_error? : (String) -> Unit, content_type? : String) -> Unit

    POST request; JSON bodies get a JSON content type.

    P5::hue

    fn[C : ColorArg] P5::hue(self : P5, c : C) -> Double

    Hue of a color (HSB/HSL range when in those modes, HSL otherwise).

    P5::image

    fn[I : ImageSource] P5::image(self : P5, img : I, x : Double, y : Double, w? : Double, h? : Double, fit? : ImageFit, x_align? : HAlign, y_align? : VAlign) -> Unit

    Draws an image (or graphics buffer) at (x, y), optionally scaled to w×h, following image_mode().

    P5::image_light

    fn[I : ImageSource] P5::image_light(self : P5, img : I) -> Unit

    Lights the scene with an image of its surroundings (imageLight); an equirectangular 360° photo works best. Shiny materials reflect it. Like other lights, call it every frame.

    P5::image_mode

    fn P5::image_mode(self : P5, mode :
    ShapeMode
    ) -> Unit

    Sets how image() interprets its position and size arguments (Corner, Corners or Center).

    P5::image_region

    fn[I : ImageSource] P5::image_region(self : P5, img : I, dx : Double, dy : Double, dw : Double, dh : Double, sx : Double, sy : Double, sw : Double, sh : Double, fit? : ImageFit, x_align? : HAlign, y_align? : VAlign) -> Unit

    Draws the source rectangle (sx, sy, sw, sh) of an image into the destination rectangle (dx, dy, dw, dh) (interpreted with image_mode()).

    P5::image_shader

    fn P5::image_shader(self : P5, s :
    Shader
    ) -> Unit

    Uses s to draw images (imageShader()).

    P5::instances

    fn P5::instances(self : P5, count : Int, f : () -> Unit) -> Unit

    Draws everything f draws count times in one call each, for shaders that place copies using gl_InstanceID (instances(count).sphere() in p5.js). Needs WebGL 2.

    P5::is_fullscreen

    fn P5::is_fullscreen(_self : P5) -> Bool

    Whether the page is in full-screen mode.

    P5::is_looping

    fn P5::is_looping(self : P5) -> Bool

    Whether draw is called every frame.

    P5::is_recording

    fn P5::is_recording(self : P5) -> Bool

    Whether the sketch is being recorded with record.

    P5::is_webgl

    fn P5::is_webgl(self : P5) -> Bool

    Whether the sketch draws with WebGL.

    P5::key_is_down

    fn P5::key_is_down(self : P5, key : String) -> Bool

    Whether a key is currently held, by key value ("a", "ArrowLeft", "Shift") or physical code ("KeyA", "Space").

    P5::lerp_color

    Blends two colors, interpolating in the current color mode.

    P5::light_falloff

    fn P5::light_falloff(self : P5, constant : Double, linear : Double, quadratic : Double) -> Unit

    Sets how point and spot lights fade with distance.

    P5::lightness

    fn[C : ColorArg] P5::lightness(self : P5, c : C) -> Double

    HSL lightness of a color.

    P5::lights

    fn P5::lights(self : P5) -> Unit

    Default lighting: gray ambient plus a gray light from the front.

    P5::line

    fn P5::line(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, z1? : Double, z2? : Double) -> Unit

    Draws a straight line between two points.

    P5::line_perspective

    fn P5::line_perspective(self : P5, on : Bool) -> Unit

    Whether strokes get thinner with distance (perspective lines).

    P5::load_bytes

    fn P5::load_bytes(self : P5, url : String, on_load : (Bytes) -> Unit) -> Unit

    Loads a file as raw bytes. In preload, setup waits for it.

    P5::load_filter_shader

    fn P5::load_filter_shader(self : P5, frag_url : String, on_load? : (
    Shader
    ) -> Unit) ->
    Shader

    Loads a filter shader's fragment source (loadFilterShader with GLSL).

    P5::load_font

    fn P5::load_font(self : P5, url : String, family? : String, on_load? : (Font) -> Unit) -> Font

    Loads a font file (.ttf, .otf, .woff; .woff2 draws but has no glyph data). The file is parsed for text_to_points and registered with the browser for drawing. In preload, setup waits for it.

    P5::load_image

    fn P5::load_image(self : P5, url : String, on_load? : (Image) -> Unit) -> Image

    Loads an image from a URL. The returned image is 1×1 until it has loaded; when called in preload, setup waits for it. Animated GIFs are decoded frame by frame and play when drawn with image().

    P5::load_json

    fn P5::load_json(self : P5, url : String, on_load : (
    Json
    ) -> Unit) -> Unit

    Loads and parses a JSON file, then calls on_load with the value.

    P5::load_model

    fn P5::load_model(self : P5, path : String, normalize? : Bool, flip_u? : Bool, flip_v? : Bool, on_load? : (
    Geometry
    ) -> Unit) ->
    Geometry

    Loads an OBJ or STL model. The returned geometry fills in when the file has loaded (in preload, setup waits). normalize scales it to fit 200 units around the origin.

    P5::load_pixels

    fn P5::load_pixels(self : P5) -> Unit

    Loads the canvas pixels into pixels (RGBA bytes, row by row, in device pixels: the array is pixel_density² times larger than width×height).

    P5::load_shader

    fn P5::load_shader(self : P5, vert_url : String, frag_url : String, on_load? : (
    Shader
    ) -> Unit) ->
    Shader

    Loads a vertex and a fragment shader file (loadShader). The shader is returned right away and gets its sources when the files arrive; in preload, setup waits for them.

    P5::load_strings

    fn P5::load_strings(self : P5, url : String, on_load? : (Array[String]) -> Unit) -> Array[String]

    Loads a text file as lines. The returned array is filled when loading finishes; in preload, setup waits for it.

    P5::load_svg

    fn P5::load_svg(self : P5, url : String, on_load : (ShapeCollection) -> Unit) -> Unit

    Loads an SVG file into a shape collection. In preload, setup waits for it.

    P5::load_table

    fn P5::load_table(self : P5, url : String, on_load : (
    Table
    ) -> Unit, header? : Bool, separator? : Char) -> Unit

    Loads a CSV (or TSV with separator='\t') file into a table. With header, the first row holds the column titles. In preload, setup waits for it.

    P5::load_text

    fn P5::load_text(self : P5, url : String, on_load? : (String) -> Unit) -> Unit

    Loads a text file and calls on_load with its contents.

    P5::load_xml

    fn P5::load_xml(self : P5, url : String, on_load : (
    Xml
    ) -> Unit) -> Unit

    Loads and parses an XML file. In preload, setup waits for it.

    P5::loop_

    fn P5::loop_(self : P5) -> Unit

    Resumes calling draw every frame.

    P5::metalness

    fn P5::metalness(self : P5, metallic : Double) -> Unit

    How metallic the material looks.

    P5::millis

    fn P5::millis(self : P5) -> Double

    Milliseconds since the sketch started drawing.

    P5::model

    fn P5::model(self : P5, g :
    Geometry
    , count? : Int) -> Unit

    Draws a geometry (model()).

    P5::no_canvas

    fn P5::no_canvas(self : P5) -> Unit

    Removes the sketch's canvas from the page; the sketch keeps running (noCanvas).

    P5::no_cursor

    fn P5::no_cursor(self : P5) -> Unit

    Hides the cursor over the canvas.

    P5::no_debug_mode

    fn P5::no_debug_mode(self : P5) -> Unit

    Turns debug_mode off.

    P5::no_erase

    fn P5::no_erase(self : P5) -> Unit

    Stops erasing.

    P5::no_fill

    fn P5::no_fill(self : P5) -> Unit

    Disables filling shapes.

    P5::no_lights

    fn P5::no_lights(self : P5) -> Unit

    Removes all lights.

    P5::no_loop

    fn P5::no_loop(self : P5) -> Unit

    Stops calling draw every frame.

    P5::no_smooth

    fn P5::no_smooth(self : P5) -> Unit

    Disables antialiasing of images (crisp pixel art scaling).

    P5::no_stroke

    fn P5::no_stroke(self : P5) -> Unit

    Disables drawing outlines.

    P5::no_tint

    fn P5::no_tint(self : P5) -> Unit

    Removes the tint.

    P5::noise

    fn P5::noise(self : P5, x : Double, y? : Double, z? : Double) -> Double

    Perlin noise in [0, 1) at (x, y, z).

    P5::noise_detail

    fn P5::noise_detail(self : P5, lod : Int, falloff? : Double) -> Unit

    Adjusts the character of noise(): number of octaves and falloff.

    P5::noise_seed

    fn P5::noise_seed(self : P5, seed : Double) -> Unit

    Sets the seed of noise().

    P5::normal

    fn P5::normal(self : P5, x : Double, y : Double, z : Double) -> Unit

    Sets the normal of vertices added afterwards (WEBGL).

    P5::normal_material

    fn P5::normal_material(self : P5) -> Unit

    Colors surfaces by their normals (x, y, z → red, green, blue).

    P5::normal_texture

    fn[I : ImageSource] P5::normal_texture(self : P5, img : I?, scale? : Double) -> Unit

    Tilts the surface normals with a tangent-space normal map (the bluish kind), scale setting its strength (normalTexture). None clears.

    P5::orbit_control

    fn P5::orbit_control(self : P5, sensitivity_x? : Double, sensitivity_y? : Double, sensitivity_z? : Double) -> Unit

    Lets the mouse (drag to rotate, right-drag to move, wheel to zoom) or touches (one finger rotates, two pinch and move) control the camera, with p5's damping. Call it in draw().

    P5::ortho

    fn P5::ortho(self : P5, left? : Double, right? : Double, bottom? : Double, top? : Double, near? : Double, far? : Double) -> Unit

    Sets an orthographic projection.

    P5::panorama

    fn[I : ImageSource] P5::panorama(self : P5, img : I) -> Unit

    Draws a 360° equirectangular image as the background, as seen through the camera (panorama). Call it at the start of draw.

    P5::perspective

    fn P5::perspective(self : P5, fovy? : Double, aspect? : Double, near? : Double, far? : Double) -> Unit

    Sets a perspective projection (fovy in the current angle mode).

    P5::pixel_density

    fn P5::pixel_density(self : P5, d : Double) -> Unit

    Sets the pixel density (device pixels per CSS pixel); this resizes and clears the canvas.

    P5::plane

    fn P5::plane(self : P5, w? : Double, h? : Double, detail_x? : Int, detail_y? : Int) -> Unit

    A plane of w × h (default 50 × w) centered at the origin.

    P5::point

    fn P5::point(self : P5, x : Double, y : Double, z? : Double) -> Unit

    Draws a point. Its size is the stroke weight; it uses the stroke color.

    P5::point_light

    fn[C : ColorArg] P5::point_light(self : P5, c : C, x : Double, y : Double, z : Double) -> Unit

    Adds a point light at (x, y, z).

    P5::point_vec

    fn P5::point_vec(self : P5, v :
    Vector
    ) -> Unit

    Draws a point at a vector's position.

    P5::pop

    fn P5::pop(self : P5) -> Unit

    Restores the style and transform saved by the last push() (and removes any clipping started since).

    P5::push

    fn P5::push(self : P5) -> Unit

    Saves the drawing style and transform.

    P5::quad

    fn P5::quad(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double, x4 : Double, y4 : Double) -> Unit

    Draws a quadrilateral.

    P5::quadratic_vertex

    fn P5::quadratic_vertex(self : P5, cx : Double, cy : Double, x : Double, y : Double) -> Unit

    p5.js 1.x style quadraticVertex(cx, cy, x, y).

    P5::random

    fn P5::random(self : P5) -> Double

    A random number in [0, 1).

    P5::random2d

    fn P5::random2d(self : P5) ->
    Vector

    A random 2D unit vector using the sketch's random generator.

    P5::random3d

    fn P5::random3d(self : P5) ->
    Vector

    A random 3D unit vector using the sketch's random generator.

    P5::random_choice

    fn[T] P5::random_choice(self : P5, choices : ArrayView[T]) -> T

    A random element of choices.

    P5::random_gaussian

    fn P5::random_gaussian(self : P5, mean? : Double, sd? : Double) -> Double

    A random number from a normal distribution.

    P5::random_max

    fn P5::random_max(self : P5, max : Double) -> Double

    A random number in [0, max).

    P5::random_range

    fn P5::random_range(self : P5, min : Double, max : Double) -> Double

    A random number in [min, max).

    P5::random_seed

    fn P5::random_seed(self : P5, seed : Double) -> Unit

    Sets the seed of random() and random_gaussian().

    P5::record

    fn P5::record(self : P5, frames~ : Int, fps? : Double, endpoint? : String, on_done? : () -> Unit) -> Unit

    Records the sketch instead of running it live: draw is called frames times, as fast as possible, with delta_time, millis() and get_frame_rate() advancing as if it ran at exactly fps. After each frame the canvas is uploaded as a PNG to endpoint (?frame=N), and endpoint + "/done" is notified at the end.

    Call it in setup. Seed random and noise (e.g. run(seed=…)) for a reproducible video.

    setup=p => {
    p.create_canvas(1920, 1080)
    p.pixel_density(1)
    if @p5.query_param("record") is Some(_) {
    p.record(frames=1200)
    }
    }

    P5::rect

    fn P5::rect(self : P5, x : Double, y : Double, w : Double, h : Double, tl? : Double, tr? : Double, br? : Double, bl? : Double) -> Unit

    Draws a rectangle. Its meaning depends on rect_mode() (corner by default). Optional corner radii round the corners: tl alone rounds all corners; tr, br, bl default to the previous radius.

    P5::rect_mode

    fn P5::rect_mode(self : P5, mode :
    ShapeMode
    ) -> Unit

    Sets how rect() interprets its arguments.

    P5::red

    fn[C : ColorArg] P5::red(self : P5, c : C) -> Double

    Red component of a color, in the current RGB range.

    P5::redraw

    fn P5::redraw(self : P5, n? : Int) -> Unit

    Runs draw n times (once by default), e.g. after no_loop().

    P5::remove

    fn P5::remove(self : P5) -> Unit

    Removes the sketch's canvas from the page and stops the draw loop.

    P5::remove_elements

    fn P5::remove_elements(self : P5) -> Unit

    Removes every element created with the create_* functions (the canvas stays).

    P5::renderer_type

    fn P5::renderer_type(self : P5) -> RendererKind

    The renderer of the canvas (rendererType).

    P5::request_pointer_lock

    fn P5::request_pointer_lock(self : P5) -> Bool

    Locks the pointer to the canvas (hiding it); moved_x/moved_y keep reporting movement. Must be called from a user gesture. Returns false when the browser doesn't support it.

    P5::reset_matrix

    fn P5::reset_matrix(self : P5) -> Unit

    Resets the coordinate system to the identity.

    P5::reset_shader

    fn P5::reset_shader(self : P5) -> Unit

    Back to the default shaders.

    P5::resize_canvas

    fn P5::resize_canvas(self : P5, w : Double, h : Double) -> Unit

    Resizes the canvas, keeping the drawing state (the contents are cleared).

    P5::rng

    Random number generator used by random().

    P5::roll

    fn P5::roll(self : P5, angle : Double) -> Unit

    Rotates the active camera about its viewing direction (the current angle mode applies).

    P5::rotate

    fn P5::rotate(self : P5, angle : Double) -> Unit

    Rotates the coordinate system by angle (in the current angle mode).

    P5::rotate_axis

    fn P5::rotate_axis(self : P5, angle : Double, x : Double, y : Double, z : Double) -> Unit

    Rotates about an arbitrary axis (WEBGL).

    P5::rotate_x

    fn P5::rotate_x(self : P5, angle : Double) -> Unit

    Rotates about the x-axis (WEBGL).

    P5::rotate_y

    fn P5::rotate_y(self : P5, angle : Double) -> Unit

    Rotates about the y-axis (WEBGL).

    P5::rotate_z

    fn P5::rotate_z(self : P5, angle : Double) -> Unit

    Rotates about the z-axis.

    P5::saturation

    fn[C : ColorArg] P5::saturation(self : P5, c : C) -> Double

    Saturation of a color.

    P5::save_canvas

    fn P5::save_canvas(self : P5, filename? : String, ext? : String) -> Unit

    Saves the canvas as an image file (png by default, or jpg/webp).

    P5::save_frames

    fn P5::save_frames(self : P5, filename : String, ext : String, duration? : Double, fps? : Double, on_done? : (Array[SavedFrame]) -> Unit) -> Unit

    Captures the canvas fps times per second for duration seconds (at most 15 s and 22 fps, as in p5). With on_done, the frames are handed to it; otherwise each one is downloaded.

    P5::save_gif

    fn P5::save_gif(self : P5, filename : String, duration : Double, delay? : Double, units? : String, silent? : Bool, reset? : Bool, on_done? : () -> Unit) -> Unit

    Records the sketch for duration (seconds, or frames with units="frames") and downloads it as an animated GIF, like p5's saveGif(). delay skips that much at the start; with reset (the default) the frame count restarts from 0.

    P5::save_svg

    fn P5::save_svg(self : P5, coll : ShapeCollection, filename? : String) -> Unit

    Downloads a shape collection as an SVG file, like p5's saveSVG(record,filename).

    P5::save_svg_frame

    fn P5::save_svg_frame(self : P5, filename? : String) -> Unit

    Records the next frame drawn by draw and downloads it as SVG, like p5's saveSVG(filename).

    P5::scale

    fn P5::scale(self : P5, x : Double, y? : Double, z? : Double) -> Unit

    Scales the coordinate system. y defaults to x.

    P5::screen_to_world

    fn P5::screen_to_world(self : P5, x : Double, y : Double) -> (Double, Double)

    Converts a point from canvas coordinates to the current user space.

    P5::set

    fn[C : ColorArg] P5::set(self : P5, x : Double, y : Double, c : C) -> Unit

    Sets a pixel in pixels (loading them first if needed); call update_pixels() to show the change.

    P5::set_attributes

    fn P5::set_attributes(self : P5, attrs : ArrayView[GlAttribute]) -> Unit

    Changes WebGL context attributes (setAttributes). Call it in setup right after create_canvas: the context is recreated, so GPU resources made before are lost.

    P5::set_camera

    fn P5::set_camera(self : P5, cam :
    Camera
    ) -> Unit

    Makes cam the active camera.

    P5::set_draw

    fn P5::set_draw(self : P5, draw : (P5) -> Unit) -> Unit

    Sets the function called by redraw() (for headless sketches).

    P5::set_move_threshold

    fn P5::set_move_threshold(self : P5, v : Double) -> Unit

    Sets how much acceleration change fires device_moved (default 0.5).

    P5::set_shake_threshold

    fn P5::set_shake_threshold(self : P5, v : Double) -> Unit

    Sets how much acceleration change fires device_shaken (default 30).

    P5::set_uniform

    fn P5::set_uniform(self : P5, s :
    Shader
    , name : String, values : ArrayView[Double]) -> Unit

    Sets a numeric uniform (scalar, vector, matrix or array).

    P5::set_uniform_texture

    fn[I : ImageSource] P5::set_uniform_texture(self : P5, s :
    Shader
    , name : String, img : I) -> Unit

    Sets a sampler uniform to an image, video or graphics.

    P5::shader

    fn P5::shader(self : P5, s :
    Shader
    ) -> Unit

    Uses s to fill shapes drawn afterwards (shader()).

    P5::shape

    fn P5::shape(self : P5, coll : ShapeCollection, x? : Double, y? : Double, scale? : Double, scale_x? : Double, scale_y? : Double, align? : ShapeAlign) -> Unit

    Draws a shape collection at (x, y), optionally scaled, aligned by align (like p5's shape(record, x, y, { align, scale })).

    P5::shear_x

    fn P5::shear_x(self : P5, angle : Double) -> Unit

    Shears along the x-axis by angle (in the current angle mode).

    P5::shear_y

    fn P5::shear_y(self : P5, angle : Double) -> Unit

    Shears along the y-axis by angle (in the current angle mode).

    P5::shininess

    fn P5::shininess(self : P5, shine : Double) -> Unit

    How glossy specular highlights are (at least 1).

    P5::shininess_texture

    fn[I : ImageSource] P5::shininess_texture(self : P5, img : I?) -> Unit

    Scales shininess across the surface by an image's red channel (shininessTexture). None clears.

    P5::shuffle

    fn[T] P5::shuffle(self : P5, arr : ArrayView[T]) -> Array[T]

    Returns a shuffled copy of arr (Fisher-Yates with the sketch's random generator, like p5's shuffle).

    P5::sin

    fn P5::sin(self : P5, angle : Double) -> Double

    Sine of an angle in the current angle mode.

    P5::smooth

    fn P5::smooth(self : P5) -> Unit

    Enables antialiasing of images (default).

    P5::specular_color

    fn[C : ColorArg] P5::specular_color(self : P5, c : C) -> Unit

    Sets the specular color of lights created afterwards.

    P5::specular_material

    fn[C : ColorArg] P5::specular_material(self : P5, c : C) -> Unit

    The color of specular highlights.

    P5::specular_texture

    fn[I : ImageSource] P5::specular_texture(self : P5, img : I?) -> Unit

    Uses an image to scale the specular color across the surface (specularTexture); also turns on the specular material. None clears.

    P5::sphere

    fn P5::sphere(self : P5, r? : Double, detail_x? : Int, detail_y? : Int) -> Unit

    A sphere of radius r (default 50).

    P5::spline

    fn P5::spline(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double, x4 : Double, y4 : Double) -> Unit

    Draws a Catmull-Rom spline segment between (x2, y2) and (x3, y3); the first and last points are control points.

    P5::spline_ends

    fn P5::spline_ends(self : P5, ends :
    SplineEnds
    ) -> Unit

    Sets how splines treat their first and last vertices.

    P5::spline_point

    fn P5::spline_point(self : P5, a : Double, b : Double, c : Double, d : Double, t : Double) -> Double

    Evaluates a spline coordinate using the current tightness.

    P5::spline_properties

    fn P5::spline_properties(self : P5) -> (
    SplineEnds
    , Double)

    The current spline ends and tightness (splineProperties()).

    P5::spline_property

    fn P5::spline_property(self : P5, prop : SplineProperty) -> Unit

    Sets a spline property (splineProperty('ends' | 'tightness', value)).

    P5::spline_tangent

    fn P5::spline_tangent(self : P5, a : Double, b : Double, c : Double, d : Double, t : Double) -> Double

    Evaluates a spline tangent using the current tightness.

    P5::spline_tightness

    fn P5::spline_tightness(self : P5, t : Double) -> Unit

    Sets spline tightness (0 = Catmull-Rom, 1 = straight lines).

    P5::spline_vertex

    fn P5::spline_vertex(self : P5, x : Double, y : Double, z? : Double, u? : Double, v? : Double) -> Unit

    Adds a spline vertex to the current shape.

    P5::spot_light

    fn[C : ColorArg] P5::spot_light(self : P5, c : C, position : (Double, Double, Double), direction : (Double, Double, Double), angle? : Double, concentration? : Double) -> Unit

    Adds a spot light at position pointing along direction; angle in the current angle mode (default π/3 radians).

    P5::square

    fn P5::square(self : P5, x : Double, y : Double, size : Double, tl? : Double, tr? : Double, br? : Double, bl? : Double) -> Unit

    Draws a square of side size.

    P5::stroke

    fn[C : ColorArg] P5::stroke(self : P5, c : C) -> Unit

    Sets the stroke (outline) color.

    P5::stroke_cap

    fn P5::stroke_cap(self : P5, cap : StrokeCap) -> Unit

    Sets the style of line ends.

    P5::stroke_join

    fn P5::stroke_join(self : P5, join : StrokeJoin) -> Unit

    Sets the style of line joints.

    P5::stroke_mode

    fn P5::stroke_mode(self : P5, mode : StrokeMode) -> Unit

    Sets how strokes are drawn in WEBGL.

    P5::stroke_shader

    fn P5::stroke_shader(self : P5, s :
    Shader
    ) -> Unit

    Uses s to draw strokes (strokeShader()).

    P5::stroke_weight

    fn P5::stroke_weight(self : P5, w : Double) -> Unit

    Sets the width of lines and outlines, in pixels.

    P5::surface

    fn P5::surface(self : P5) -> &Surface

    The underlying drawing surface.

    P5::tan

    fn P5::tan(self : P5, angle : Double) -> Double

    Tangent of an angle in the current angle mode.

    P5::text

    fn P5::text(self : P5, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double) -> Unit

    Draws text at (x, y). Newlines start new lines, text_leading() apart.

    With max_width the text is wrapped inside a box (positioned according to rect_mode()); with max_height, lines that don't fit are dropped. Text uses the fill color (black unless fill was called) and is only outlined when stroke was called explicitly.

    P5::text_align

    fn P5::text_align(self : P5, horizontal : HAlign, vertical? : VAlign) -> Unit

    Sets horizontal and (optionally) vertical alignment.

    P5::text_ascent

    fn P5::text_ascent(self : P5, s? : String) -> Double

    Ascent of s (tight), or of the font when s is empty.

    P5::text_bounds

    fn P5::text_bounds(self : P5, s : String, x : Double, y : Double, max_width? : Double, max_height? : Double) -> Bounds

    The tight bounding box of text drawn with text(s, x, y, …), from the glyphs' actual extents.

    P5::text_descent

    fn P5::text_descent(self : P5, s? : String) -> Double

    Descent of s (tight), or of the font when s is empty.

    P5::text_direction

    fn P5::text_direction(self : P5, direction : String) -> Unit

    Sets the text direction ("ltr", "rtl" or "inherit").

    P5::text_font

    fn P5::text_font(self : P5, family : String, size? : Double) -> Unit

    Sets the font family (any CSS family list such as "Georgia, serif"), optionally with a size.

    P5::text_font_face

    fn P5::text_font_face(self : P5, font : Font, size? : Double) -> Unit

    Uses a font returned by load_font.

    P5::text_leading

    fn P5::text_leading(self : P5, leading : Double) -> Unit

    Sets the spacing between lines of text, in pixels.

    P5::text_output

    fn P5::text_output(self : P5, display? : DescriptionDisplay) -> Unit

    Describes the shapes on the canvas as a list, updated every frame: their kind, color, position and size. With display=Label the output is also shown next to the canvas. 2D only, as in p5.

    P5::text_properties

    fn P5::text_properties(self : P5, props : ArrayView[(String, String)]) -> Unit

    Sets several text properties at once (textProperties(obj)).

    P5::text_property

    fn P5::text_property(self : P5, name : String, value : String) -> Unit

    Sets a text property by its p5 / Canvas API name (textProperty): textSize, textLeading, textFont, textStyle, textWeight, textAlign, textBaseline, textWrap, textDirection/direction, fontVariant, or any text property of the 2D context such as letterSpacing, wordSpacing, fontKerning, fontStretch, fontVariantCaps and textRendering. Values are written as in CSS.

    P5::text_size

    fn P5::text_size(self : P5, size : Double) -> Unit

    Sets the font size in pixels. Unless text_leading was set, the leading becomes 1.275 × size.

    P5::text_style

    fn P5::text_style(self : P5, style : TextStyle) -> Unit

    Sets normal, italic, bold or bold-italic text.

    P5::text_variant

    fn P5::text_variant(self : P5, variant : String) -> Unit

    Sets the font variant ("normal" or "small-caps").

    P5::text_weight

    fn P5::text_weight(self : P5, weight : Double) -> Unit

    Sets the numeric font weight (100-900; 400 is normal, 700 bold).

    P5::text_width

    fn P5::text_width(self : P5, s : String) -> Double

    Tight width of a string (the widest line), like p5 2.x textWidth().

    P5::text_wrap

    fn P5::text_wrap(self : P5, wrap : TextWrap) -> Unit

    Sets how text wraps inside a box: at word or character boundaries.

    P5::texture

    fn[I : ImageSource] P5::texture(self : P5, img : I) -> Unit

    Textures shapes drawn afterwards with an image, video or graphics.

    P5::texture_interpolation

    fn[I : ImageSource] P5::texture_interpolation(self : P5, img : I, downscale : TextureFilter, upscale? : TextureFilter) -> Unit

    Sets how an image is sampled as a texture when drawn smaller (downscale) and larger (upscale): Nearest keeps pixels crisp, Linear (default) smooths them (p5.Texture's setInterpolation).

    P5::texture_mode

    fn P5::texture_mode(self : P5, mode : TextureMode) -> Unit

    Sets how texture coordinates are read: in pixels (Image) or [0, 1].

    P5::texture_wrap

    fn P5::texture_wrap(self : P5, x : TextureWrap, y? : TextureWrap) -> Unit

    Sets how textures wrap horizontally and vertically.

    P5::tint

    fn[C : ColorArg] P5::tint(self : P5, c : C) -> Unit

    Tints images drawn afterwards with a color (alpha makes them translucent).

    P5::torus

    fn P5::torus(self : P5, r? : Double, tube? : Double, detail_x? : Int, detail_y? : Int) -> Unit

    A torus of ring radius r (default 50) and tube radius tube (10).

    P5::translate

    fn P5::translate(self : P5, x : Double, y : Double, z? : Double) -> Unit

    Moves the origin by (x, y).

    P5::triangle

    fn P5::triangle(self : P5, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double) -> Unit

    Draws a triangle.

    P5::update_pixels

    fn P5::update_pixels(self : P5) -> Unit

    Writes pixels back to the canvas.

    P5::vertex

    fn P5::vertex(self : P5, x : Double, y : Double, z? : Double, u? : Double, v? : Double) -> Unit

    Adds a vertex to the current shape.

    P5::vertex_property

    fn P5::vertex_property(self : P5, name : String, data : ArrayView[Double]) -> Unit

    Sets a custom per-vertex value for the vertices added after it in the current shape (vertexProperty). Shaders read it as an attribute named name with as many components as data has. Call it before the shape's first vertex so every vertex gets a value.

    P5::webgl_version

    fn P5::webgl_version(self : P5) -> String

    "webgl2" or "webgl" for a WEBGL canvas, "p2d" otherwise (p5's webglVersion).

    P5::with_push

    fn P5::with_push(self : P5, body : () -> Unit) -> Unit

    Runs body between push() and pop().

    P5::world_to_screen

    fn P5::world_to_screen(self : P5, x : Double, y : Double) -> (Double, Double)

    Converts a point from the current user space to canvas coordinates.

    PrintWriter

    pub struct PrintWriter {
    // private fields
    }

    Accumulates text and downloads it as a file on close() (p5's createWriter / p5.PrintWriter).

    PrintWriter::clear

    fn PrintWriter::clear(self : PrintWriter) -> Unit

    Discards what was written.

    PrintWriter::close

    fn PrintWriter::close(self : PrintWriter) -> Unit

    Downloads the file.

    PrintWriter::print

    fn PrintWriter::print(self : PrintWriter, text : String) -> Unit

    Appends text and a newline.

    PrintWriter::write

    fn PrintWriter::write(self : PrintWriter, text : String) -> Unit

    Appends text.

    Recorder

    pub struct Recorder {
    log : Array[String]
    // private fields
    }

    A surface that records every drawing call as a line of text. Text is measured as 0.5 * size per character. Pixel reads return zeros.
    impl Surface for Recorder

    Recorder::new

    fn Recorder::new() -> Recorder

    Creates an empty recorder.

    Recorder::take

    fn Recorder::take(self : Recorder) -> Array[String]

    Returns the recorded calls and clears the log.

    RendererKind

    pub(all) enum RendererKind {
    P2D
    WebGL
    P2DP3
    }

    The renderer of the main canvas.

    SavedFrame

    pub(all) struct SavedFrame {
    image_data : String
    filename : String
    ext : String
    }

    A frame captured by save_frames.

    ShapeAlign

    pub(all) enum ShapeAlign {
    AlignCorner
    AlignCenter
    AlignViewBox
    } derive(Eq,
    Debug
    )

    How shape() aligns a collection with (x, y).

    ShapeCollection

    pub struct ShapeCollection {
    ops : Array[DrawOp]
    bounds : (Double, Double, Double, Double)
    // private fields
    }

    Recorded drawing commands (p5.ShapeCollection): replay them with shape(), or export them with get_svg() / save_svg().

    ShapeCollection::begin

    fn ShapeCollection::begin(self : ShapeCollection, p : P5, draw? : Bool) -> Unit

    Starts recording what the sketch p draws into this collection; with draw it is drawn on the canvas too. Stop with end.

    ShapeCollection::end

    fn ShapeCollection::end(self : ShapeCollection) -> Unit

    Stops recording (see begin); the commands are added to the collection.

    SplineProperty

    pub(all) enum SplineProperty {
    Ends(
    SplineEnds
    )
    Tightness(Double)
    }

    A spline setting for spline_property.

    StrokeCap

    pub(all) enum StrokeCap {
    Round
    Square
    Project
    } derive(Eq,
    Debug
    )

    strokeCap() values.

    StrokeJoin

    pub(all) enum StrokeJoin {
    Miter
    Bevel
    RoundJoin
    } derive(Eq,
    Debug
    )

    strokeJoin() values.

    StrokeMode

    pub(all) enum StrokeMode {
    Simple
    Full
    } derive(Eq,
    Debug
    )

    How WEBGL strokes are drawn: Full (default) with caps and joins, or Simple, faster plain lines.

    TextMetrics

    pub(all) struct TextMetrics {
    width : Double
    actual_left : Double
    actual_right : Double
    actual_ascent : Double
    actual_descent : Double
    font_ascent : Double
    font_descent : Double
    alphabetic_baseline : Double
    } derive(
    Debug
    )

    Text measurements, as returned by the canvas measureText().

    TextPoint

    pub(all) struct TextPoint {
    x : Double
    y : Double
    angle : Double
    } derive(
    Debug
    )

    A point on a text outline from text_to_points, with the path angle in the current angle mode.

    TextPoint::alpha

    fn TextPoint::alpha(self : TextPoint) -> Double

    p5's backwards-compatible name for angle.

    TextStyle

    pub(all) enum TextStyle {
    Normal
    Italic
    Bold
    BoldItalic
    } derive(Eq,
    Debug
    )

    textStyle() values.

    TextWrap

    pub(all) enum TextWrap {
    Word
    Char
    } derive(Eq,
    Debug
    )

    textWrap() values.

    TextureFilter

    pub(all) enum TextureFilter {
    Nearest
    Linear
    } derive(Eq,
    Debug
    )

    How a texture is sampled (p5's NEAREST and LINEAR).

    TextureMode

    pub(all) enum TextureMode {
    Image
    Normal
    }

    How texture coordinates passed to vertex() are read.

    TextureWrap

    pub(all) enum TextureWrap {
    Clamp
    Repeat
    Mirror
    }

    How textures repeat outside [0, 1].

    Touch

    pub(all) struct Touch {
    x : Double
    y : Double
    win_x : Double
    win_y : Double
    id : Int
    } derive(Eq,
    Debug
    )

    An active touch point.

    VAlign

    pub(all) enum VAlign {
    Top
    VCenter
    Bottom
    Baseline
    Hanging
    Ideographic
    } derive(Eq,
    Debug
    )

    Vertical text alignment (textAlign(..., v)).

    DEG_TO_RAD

    let DEG_TO_RAD : Double

    Multiply an angle in degrees by this value to convert it to radians.

    HALF_PI

    let HALF_PI : Double

    Half of the mathematical constant π (≈ 1.5708).
    let PI : Double

    The mathematical constant π (≈ 3.14159).

    QUARTER_PI

    let QUARTER_PI : Double

    A quarter of π (≈ 0.7854).

    RAD_TO_DEG

    let RAD_TO_DEG : Double

    Multiply an angle in radians by this value to convert it to degrees.

    TAU

    let TAU : Double

    An alias for TWO_PI.

    TWO_PI

    let TWO_PI : Double

    Twice π (≈ 6.28319).

    bezier_point

    fn bezier_point(a : Double, b : Double, c : Double, d : Double, t : Double) -> Double

    Evaluates one coordinate of a cubic Bézier curve at t.

    test {
    inspect(@shape.bezier_point(0, 0, 100, 100, 0.5), content="50")
    }

    bezier_tangent

    fn bezier_tangent(a : Double, b : Double, c : Double, d : Double, t : Double) -> Double

    Evaluates the derivative of one coordinate of a cubic Bézier at t.

    binary

    fn binary(n : Int, digits? : Int) -> String

    Binary representation, digits long (8 by default).

    clear_storage

    fn clear_storage() -> Unit

    Removes every value stored with store_item (keys with a p5 type tag), like p5's clearStorage().

    constrain

    fn constrain(n : Double, low : Double, high : Double) -> Double

    Constrains n between low and high.

    test {
    inspect(@math.constrain(15, 0, 10), content="10")
    inspect(@math.constrain(-1, 0, 10), content="0")
    }

    create_svg

    fn create_svg(markup : String) -> ShapeCollection raise
    XmlError

    Parses SVG markup into a shape collection, like p5's createSVG().

    day

    fn day() -> Int

    The current day of the month (1-31).

    degrees

    fn degrees(rad : Double) -> Double

    Converts an angle from radians to degrees.

    dist

    fn dist(x1 : Double, y1 : Double, x2 : Double, y2 : Double) -> Double

    Distance between two 2D points.

    dist3

    fn dist3(x1 : Double, y1 : Double, z1 : Double, x2 : Double, y2 : Double, z2 : Double) -> Double

    Distance between two 3D points.

    exp

    fn exp(x : Double) -> Double

    e raised to x (p5's exp).

    fract

    fn fract(n : Double) -> Double

    Fractional part of a number: fract(3.75) == 0.75, fract(-1.25) == 0.75.

    get_item

    fn get_item(key : String) -> String?

    Reads a stored value as a string (None when missing).

    get_item_bool

    fn get_item_bool(key : String) -> Bool?

    Reads a stored boolean.

    get_item_color

    fn get_item_color(key : String) ->
    Color
    ?

    Reads a stored color.

    get_item_json

    fn get_item_json(key : String) ->
    Json
    ?

    Reads a stored JSON value.

    get_item_number

    fn get_item_number(key : String) -> Double?

    Reads a stored number (parseFloat).

    get_item_vector

    fn get_item_vector(key : String) ->
    Vector
    ?

    Reads a stored vector.

    hex

    fn hex(n : Int, digits? : Int) -> String

    Hexadecimal representation (uppercase, digits long, two's complement for negative numbers).

    test {
    inspect(@p5.hex(255, digits=2), content="FF")
    inspect(@p5.hex(-1), content="FFFFFFFF")
    inspect(@p5.unhex("ff"), content="255")
    }

    hour

    fn hour() -> Int

    The current hour (0-23).

    js_rem

    fn js_rem(a : Double, b : Double) -> Double

    JavaScript % on doubles (result has the sign of the dividend).

    lerp

    fn lerp(start : Double, stop : Double, amt : Double) -> Double

    Linear interpolation: amt * (stop - start) + start.

    log

    fn log(x : Double) -> Double

    Natural logarithm (p5's log).

    mag

    fn mag(x : Double, y : Double) -> Double

    Length of the 2D vector (x, y).

    map

    fn map(n : Double, start1 : Double, stop1 : Double, start2 : Double, stop2 : Double, within_bounds? : Bool) -> Double

    Re-maps n from the range [start1, stop1] to [start2, stop2]. When within_bounds is true the result is constrained to the target range.

    test {
    inspect(@math.map(5, 0, 10, 0, 100), content="50")
    inspect(@math.map(20, 0, 10, 0, 100, within_bounds=true), content="100")
    }

    max_of

    fn max_of(values : ArrayView[Double]) -> Double

    Largest value of an array (-inf when empty).

    min_of

    fn min_of(values : ArrayView[Double]) -> Double

    Smallest value of an array (inf when empty).

    minute

    fn minute() -> Int

    The current minute (0-59).

    month

    fn month() -> Int

    The current month (1-12).
    fn nf(num : Double, left? : Int, right? : Int) -> String

    Formats a number with at least left digits before the decimal point (zero-padded) and, when given, exactly right digits after it.

    test {
    inspect(@p5.nf(42, left=4), content="0042")
    inspect(@p5.nf(3.14159, left=2, right=2), content="03.14")
    inspect(@p5.nf(-7.5, left=3), content="-007.5")
    }

    nfc

    fn nfc(num : Double, right? : Int) -> String

    Formats a number with commas between groups of thousands and, when given, right digits after the decimal point (truncated or padded).

    test {
    inspect(@p5.nfc(1234567.891, right=2), content="1,234,567.89")
    inspect(@p5.nfc(1000), content="1,000")
    }

    nfp

    fn nfp(num : Double, left? : Int, right? : Int) -> String

    Like nf, but adds a + in front of positive numbers.

    nfs

    fn nfs(num : Double, left? : Int, right? : Int) -> String

    Like nf, but adds a space in front of non-negative numbers so they line up with negative ones.

    norm

    fn norm(n : Double, start : Double, stop : Double) -> Double

    Normalizes n from the range [start, stop] to [0, 1].

    palette_lerp

    fn palette_lerp(stops : ArrayView[(
    Color
    , Double)], amt : Double) ->
    Color

    Picks a color along a list of (color, stop) pairs, like p5's paletteLerp(). Stops must be increasing.

    Panics

    Panics if stops is empty.

    parse_float

    fn parse_float(s : String) -> Double

    JavaScript parseFloat: the longest numeric prefix, NaN when none.

    parse_svg_path

    fn parse_svg_path(d : String) -> Array[
    PathCmd
    ]

    Parses SVG path data into canvas path commands.

    pow

    fn pow(base : Double, exponent : Double) -> Double

    base raised to exponent (p5's pow).

    print

    fn print(msg : String) -> Unit

    Prints a message to the browser console.

    query_param

    fn query_param(name : String) -> String?

    The value of a query parameter of the page URL (?name=value), or None when it is absent.

    radians

    fn radians(deg : Double) -> Double

    Converts an angle from degrees to radians.

    remove_item

    fn remove_item(key : String) -> Unit

    Removes a stored value and its type tag.

    round

    fn round(n : Double, decimals? : Int) -> Double

    Rounds n to the given number of decimals (0 by default), with JavaScript Math.round semantics.

    test {
    inspect(@math.round(2.5), content="3")
    inspect(@math.round(-2.5), content="-2")
    inspect(@math.round(3.14159, decimals=2), content="3.14")
    }

    run

    fn run(preload? : (P5) -> Unit, setup? : (P5) -> Unit, draw? : (P5) -> Unit, mouse_pressed? : (P5) -> Unit, mouse_released? : (P5) -> Unit, mouse_clicked? : (P5) -> Unit, double_clicked? : (P5) -> Unit, mouse_moved? : (P5) -> Unit, mouse_dragged? : (P5) -> Unit, mouse_wheel? : (P5, Double) -> Unit, key_pressed? : (P5) -> Unit, key_released? : (P5) -> Unit, key_typed? : (P5) -> Unit, touch_started? : (P5) -> Unit, touch_moved? : (P5) -> Unit, touch_ended? : (P5) -> Unit, window_resized? : (P5) -> Unit, device_moved? : (P5) -> Unit, device_turned? : (P5) -> Unit, device_shaken? : (P5) -> Unit, container? : String, seed? : Double) -> Unit

    Starts a sketch in the browser, like creating new p5(sketch).

    A 100×100 canvas is created before setup runs (call create_canvas in setup to resize it). preload may start asset loads such as load_image; setup runs once they have all finished. Then draw is called once per frame. Every callback is optional.

    container is the id of an element to put the canvas in (by default the canvas goes into <main>). seed seeds random() and noise() (random by default).

    fn main {
    @p5.run(setup=p => p.create_canvas(400, 400), draw=p => {
    p.background(220)
    p.circle(p.mouse_x, p.mouse_y, 50)
    })
    }

    save_json

    fn save_json(value :
    Json
    , filename : String, pretty? : Bool) -> Unit

    Downloads a JSON value as a file.

    save_strings

    fn save_strings(lines : ArrayView[String], filename : String, ext? : String) -> Unit

    Downloads lines of text as a file.

    save_table

    fn save_table(table :
    Table
    , filename : String, ext? : String) -> Unit

    Downloads a table as csv (default), tsv or html.

    save_xml

    fn save_xml(xml :
    Xml
    , filename : String) -> Unit

    Downloads an XML tree as a file.

    second

    fn second() -> Int

    The current second (0-59).

    select

    fn select(selector : String) -> Element?

    Selects the first element matching a CSS selector.

    select_all

    fn select_all(selector : String, container? : String) -> Array[Element]

    All elements matching a CSS selector (inside the element matching container, if given).

    set_title

    fn set_title(title : String) -> Unit

    Sets the document title.

    spline_point

    fn spline_point(a : Double, b : Double, c : Double, d : Double, t : Double, tightness? : Double) -> Double

    Evaluates one coordinate of a Catmull-Rom spline segment between b and c at t, with the given tightness (0 by default).

    spline_tangent

    fn spline_tangent(a : Double, b : Double, c : Double, d : Double, t : Double, tightness? : Double) -> Double

    Evaluates the derivative of one coordinate of a spline segment at t.

    split_tokens

    fn split_tokens(s : String, delims? : String) -> Array[String]

    Splits a string at any of the characters in delims (whitespace by default), dropping empty tokens.

    test {
    debug_inspect(
    @p5.split_tokens("a, b,,c", delims=", "),
    content=(
    #|["a", "b", "c"]
    ),
    )
    }
    fn sq(n : Double) -> Double

    Squares a number.

    sqrt

    fn sqrt(x : Double) -> Double

    Square root (p5's sqrt).

    store_item

    fn[T : Storable] store_item(key : String, value : T) -> Unit

    Saves a value in the browser's local storage (with p5's type tag).

    unbinary

    fn unbinary(s : String) -> Int

    Parses a binary string (returns 0 when invalid).

    unhex

    fn unhex(s : String) -> Int

    Parses a hexadecimal string (returns 0 when invalid).

    year

    fn year() -> Int

    The current year.