Easily turn a p5.js sketch into a val. See https://www.val.town/v/saolsen/p5_sketch for an example.
- Make a p5 sketch, you can import the p5 types to make it easier.
import type * as p5 from "npm:@types/p5";
-
Export any "global" p5 functions. These are functions like setup
and draw
that p5 will call.
-
Set the val type to http and default export the result of sketch
, passing in import.meta.url
.
A full example looks like this.
import type * as p5 from "npm:@types/p5";
export function setup() {
createCanvas(400, 400);
}
export function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
import { sketch } from "https://esm.town/v/saolsen/p5";
export default sketch(import.meta.url);
The sketch function returns an http handler that sets up a basic page with p5.js added. It then imports your module from the browser and wires up all the exports so p5.js can see them. All the code in your val will run in the browser (except for the default sketch
export) so you can't call any Deno functions, environment variables, or other server side apis.