Skip to main content
100%

Fork of P5.js Starter

✓ Published0🌍 Public
AAndrew Blakeslee Moore
Last edited Feb 2, 2024
Created on Feb 2, 2024
Forked from P5.js Starter

This example demonstrates a p5.js sketch rendered in the VizHub environment with hot reloading, showing three concentric target patterns of varying gray shades on a canvas. The code imports the p5 library and manually instantiates it to bypass the default global functions, binding methods like `createCanvas`, `background`, `fill`, and `ellipse` to the p5 instance. It defines `setup` and `draw` functions within the sketch, attaching them to the instance, and uses the canvas `parent` method to attach the canvas to the container element, enabling seamless updates during development.

AI-generated description

Unlocking P5.js with hot reloading!

<video autoplay="" loop="" muted="" width="100%"> <source src="https://vizhub-images.s3.amazonaws.com/p5-demo.mp4" type="video/mp4" /> </video>

This example is copied from the P5: Functions example. Several modifications were required to make it work in VizHub with hot reloading:

  • Since VizHub uses ES modules, we can't rely on the P5 globals (like setup and draw), and we can't rely on the way P5 usually runs and interprets those.
  • Therefore in index.js, some setup is required to import P5 and manually execute the Sketch.
  • To support hot reloading, we store the sketch instance on the container DOM element, and remove the old one if it's present.
  • The sketch is defined in sketch.js as an ES module that exports a function that accepts the container element. This was required so that we can call use the P5 parent function to tell it to attach the canvas to our container element.
  • Within the sketch, we can't reference functions like createCanvas and background because we are using ES modules and not globals. However, we can "simulate" globals by extracting those functions from the p5 instance p! Since those internally reference this, we need to use bind to make sure that they work properly. If you need more p5 functions, you can follow the same pattern used here.
  • Finally, we need to attach our setup and draw functions to the p5 instance.

I've tried to make this setup mimic regular P5 in the internals as much as possible. It should, in theory, be possible to copy the code from any P5 example straight into this template. Just make sure to:

  • Set up .parent on the canvas
  • Extract the p5 instance functions you need
  • Attach your setup and draw functions

Magically, this all works pretty well with VizHub's hot reloading, so you can use Alt+drag to edit numbers and see the rendered graphic update instantly.

Enjoy!

MIT Licensed

Similar vizzes