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.
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)
},
)
}// moon.pkg
import {
"bobzhang/p5",
}
supported_targets = "js"
options(
"is-main": true,
)moon build --target js --release<main></main>
<script src="_build/js/release/build/<your-package>/<name>.js"></script>moon build --target js --release
python3 -m http.server 8765| Example | Shows |
|---|---|
| shapes | primitives, Bézier/spline curves, contours, HSB colors, transforms, text, mouse |
| images | load_image in preload, filters, tint, per-pixel edits, graphics buffers |
| flowfield | vectors, Perlin noise, sliders and buttons |
| input | keyboard, mouse, wheel, clip, erase |
| data | load_json, load_strings, CSV tables, XML |
| dom | video as pixels, radio buttons, file input, dropping files |
moon build --target js --release
python3 tools/record.py --out history.mp4| p5.js | p5.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, key | p.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 setup | p.load_image(url) in preload (setup waits for it) |
| Package | Contents | Targets |
|---|---|---|
| bobzhang/p5 | the sketch API (P5, run, Image, Element, …) | js |
| bobzhang/p5/math | Vector, Noise, Random (p5's LCG), Matrix2D, map/lerp/… | all |
| bobzhang/p5/color | Color: RGB/HSB/HSL/HWB/Lab/LCH/OKLab/OKLCH/Display P3, CSS parsing, lerp, WCAG and APCA contrast | all |
| bobzhang/p5/a11y | accessible outputs: color names, text and grid descriptions of a drawing | all |
| bobzhang/p5/shape | the p5 2.x shape model and its conversion to canvas path commands | all |
| bobzhang/p5/filters | CPU image filters (threshold, gray, invert, posterize, erode, dilate, blur) | all |
| bobzhang/p5/font | font 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/gif | GIF encoding (gifenc) and decoding (omggif) | all |
| bobzhang/p5/io | CSV, Table, XML | all |
| bobzhang/p5/webgl | the WEBGL renderer: geometry, primitives, camera, shaders, lights, image-based lighting, texture maps, framebuffers, clipping, OBJ/MTL/STL, libtess, text | js |
| bobzhang/p5/gl | a thin WebGL binding | js |
| bobzhang/p5/dom | JavaScript FFI bindings (canvas, events, images, DOM) | js |
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 …"]moon check
moon test # runs on the JS backend (Node), using the Recorder surface
moon fmt
moon info # regenerates pkg.generated.mbti| a c e |
| b d f |
| 0 0 1 |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)))pub(open) trait ImageSource {
fn image_source(Self) -> (ImageElement, Int, Int, Double, Double)?
fn advance(Self, now : Double) -> Unit = _
fn gl_source(Self) -> TexSource? = _
}impl ImageSource for Framebufferpub(open) trait Num {
fn to_num(Self) -> Double
}pub(open) trait Storable {
fn to_storage(Self) -> (String, String)
}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
}impl Surface for CanvasSurfacefn draw_image(self : CanvasSurface, img : ImageElement, iw : Int, ih : Int, tint : (Double, Double, Double, Double)?, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unitfn fill_rect(self : CanvasSurface, x : Double, y : Double, w : Double, h : Double, style : String) -> Unitfn set_text_style(self : CanvasSurface, font : String, align : HAlign, baseline : VAlign, direction : String) -> Unitfn stroke_path(self : CanvasSurface, path : Array[PathCmd], style : String, w : Double, cap : StrokeCap, join : StrokeJoin) -> Unitfn stroke_text(self : CanvasSurface, s : String, x : Double, y : Double, style : String, w : Double, join : StrokeJoin) -> Unitfn write_pixels(self : CanvasSurface, bytes : FixedArray[Byte], x : Int, y : Int, w : Int, h : Int) -> Unitimpl Surface for DisplayListfn draw_image(self : DisplayList, img : ImageElement, iw : Int, ih : Int, tint : (Double, Double, Double, Double)?, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unitfn fill_rect(self : DisplayList, x : Double, y : Double, w : Double, h : Double, style : String) -> Unitfn set_text_style(self : DisplayList, font : String, align : HAlign, baseline : VAlign, direction : String) -> Unitfn stroke_path(self : DisplayList, path : Array[PathCmd], style : String, w : Double, cap : StrokeCap, join : StrokeJoin) -> Unitfn stroke_text(self : DisplayList, s : String, x : Double, y : Double, style : String, w : Double, join : StrokeJoin) -> Unitfn write_pixels(self : DisplayList, bytes : FixedArray[Byte], x : Int, y : Int, w : Int, h : Int) -> Unitpub(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)
}pub struct File {
file : File
file_type : String
subtype : String
name : String
size : Int
data : String
// private fields
}pub(all) enum GlAttribute {
Alpha(Bool)
Depth(Bool)
Stencil(Bool)
Antialias(Bool)
PremultipliedAlpha(Bool)
PreserveDrawingBuffer(Bool)
PerPixelLighting(Bool)
Version(Int)
}pub struct Image {
width : Double
height : Double
pixels : FixedArray[Byte]
// private fields
}impl ImageSource for Imagefn[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) -> Unitfn[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) -> Unitpub struct MediaElement {
element : Element
width : Double
height : Double
pixels : FixedArray[Byte]
// private fields
}impl ImageSource for MediaElementpub 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
}impl ImageSource for P5fn[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) -> Unitfn[I : ImageSource] P5::copy(self : P5, src : I, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unitfn P5::create_audio(self : P5, sources : Array[String], on_load? : (MediaElement) -> Unit) -> MediaElementfn P5::create_capture(self : P5, video? : Bool, audio? : Bool, flipped? : Bool, on_ready? : (MediaElement) -> Unit) -> MediaElementfn P5::create_framebuffer(self : P5, width? : Double, height? : Double, density? : Double, antialias? : Int, depth? : Bool, stencil? : Bool, depth_float? : Bool, linear? : Bool) -> Framebuffer?fn P5::create_video(self : P5, sources : Array[String], on_load? : (MediaElement) -> Unit) -> MediaElementfn P5::describe_element(self : P5, name : String, text : String, display? : DescriptionDisplay, lang? : String) -> Unittest {
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
),
)
}setup=p => {
p.create_canvas(1920, 1080)
p.pixel_density(1)
if @p5.query_param("record") is Some(_) {
p.record(frames=1200)
}
}fn P5::save_frames(self : P5, filename : String, ext : String, duration? : Double, fps? : Double, on_done? : (Array[SavedFrame]) -> Unit) -> Unitfn P5::shape(self : P5, coll : ShapeCollection, x? : Double, y? : Double, scale? : Double, scale_x? : Double, scale_y? : Double, align? : ShapeAlign) -> Unitfn[I : ImageSource] P5::texture_interpolation(self : P5, img : I, downscale : TextureFilter, upscale? : TextureFilter) -> Unitpub struct PrintWriter {
// private fields
}fn draw_image(self : Recorder, _ : ImageElement, iw : Int, ih : Int, tint : (Double, Double, Double, Double)?, sx : Double, sy : Double, sw : Double, sh : Double, dx : Double, dy : Double, dw : Double, dh : Double) -> Unitfn fill_rect(self : Recorder, x : Double, y : Double, w : Double, h : Double, style : String) -> Unitfn stroke_path(self : Recorder, path : Array[PathCmd], style : String, w : Double, cap : StrokeCap, join : StrokeJoin) -> Unitfn stroke_text(self : Recorder, s : String, x : Double, y : Double, style : String, w : Double, _ : StrokeJoin) -> Unitpub(all) struct SavedFrame {
image_data : String
filename : String
ext : String
}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)pub(all) enum TextureMode {
Image
Normal
}pub(all) enum TextureWrap {
Clamp
Repeat
Mirror
}let DEG_TO_RAD : Doublelet RAD_TO_DEG : Doublefn bezier_point(a : Double, b : Double, c : Double, d : Double, t : Double) -> Doubletest {
inspect(@shape.bezier_point(0, 0, 100, 100, 0.5), content="50")
}fn bezier_tangent(a : Double, b : Double, c : Double, d : Double, t : Double) -> Doublefn binary(n : Int, digits? : Int) -> Stringfn clear_storage() -> Unitfn constrain(n : Double, low : Double, high : Double) -> Doubletest {
inspect(@math.constrain(15, 0, 10), content="10")
inspect(@math.constrain(-1, 0, 10), content="0")
}fn dist(x1 : Double, y1 : Double, x2 : Double, y2 : Double) -> Doublefn dist3(x1 : Double, y1 : Double, z1 : Double, x2 : Double, y2 : Double, z2 : Double) -> Doublefn fract(n : Double) -> Doublefn get_item(key : String) -> String?fn hex(n : Int, digits? : Int) -> Stringtest {
inspect(@p5.hex(255, digits=2), content="FF")
inspect(@p5.hex(-1), content="FFFFFFFF")
inspect(@p5.unhex("ff"), content="255")
}fn js_rem(a : Double, b : Double) -> Doublefn lerp(start : Double, stop : Double, amt : Double) -> Doublefn map(n : Double, start1 : Double, stop1 : Double, start2 : Double, stop2 : Double, within_bounds? : Bool) -> Doubletest {
inspect(@math.map(5, 0, 10, 0, 100), content="50")
inspect(@math.map(20, 0, 10, 0, 100, within_bounds=true), content="100")
}fn nf(num : Double, left? : Int, right? : Int) -> Stringtest {
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")
}fn nfc(num : Double, right? : Int) -> Stringtest {
inspect(@p5.nfc(1234567.891, right=2), content="1,234,567.89")
inspect(@p5.nfc(1000), content="1,000")
}fn nfp(num : Double, left? : Int, right? : Int) -> Stringfn nfs(num : Double, left? : Int, right? : Int) -> Stringfn norm(n : Double, start : Double, stop : Double) -> Doublefn parse_float(s : String) -> Doublefn query_param(name : String) -> String?fn round(n : Double, decimals? : Int) -> Doubletest {
inspect(@math.round(2.5), content="3")
inspect(@math.round(-2.5), content="-2")
inspect(@math.round(3.14159, decimals=2), content="3.14")
}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) -> Unitfn main {
@p5.run(setup=p => p.create_canvas(400, 400), draw=p => {
p.background(220)
p.circle(p.mouse_x, p.mouse_y, 50)
})
}fn spline_point(a : Double, b : Double, c : Double, d : Double, t : Double, tightness? : Double) -> Doublefn spline_tangent(a : Double, b : Double, c : Double, d : Double, t : Double, tightness? : Double) -> Doubletest {
debug_inspect(
@p5.split_tokens("a, b,,c", delims=", "),
content=(
#|["a", "b", "c"]
),
)
}Install
Download zipA 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.