Public
Edited
Oct 13, 2022
1 fork
1 star
Insert cell
Insert cell
// p8g can currently only initialize a WebGL2 canvas once.
// That means it can easily conflict with Observable's reactivity.
// To avoid that, use `createCanvas` to create a p8g canvas ONCE
// and don't use any reactivity in this cell
createCanvas(w, w)
Insert cell
w = 500
Insert cell
// The helper functions further below let you define a
// draw function as a regular cell, just like you would
// with Processing or P5js. It is called once per frame.
function draw(){

const {
background,
stroke,
strokeWeight,
line,
} = p8g;

const {sin, cos, tan, PI, sqrt, abs} = Math;
const TAU = PI * 2

f[0]++ // quick mutable hach for observable.
background(0)
stroke(255)
strokeWeight(3)
for(let y=0;y<600;y+=50){
for(let x=0;x<600;x+=50){
for(let i=tan(~~(abs((simplex.noise2D(x,y)-.5))*20)*f/80)/5+PI/4, I=i;i<(I+TAU);i+=PI/2){
line(x,y,x+50/sqrt(2)*cos(i),y+50/sqrt(2)*sin(i))
}
}
}
}
Insert cell
f=[0]
Insert cell
simplex = new simplexNoise(42)
Insert cell
simplexNoise = require('simplex-noise@2.4.0')
Insert cell
Insert cell
Insert cell
async function createCanvas(width, height) {
return html`${p8g.createCanvas(width, height)}`;
}
Insert cell
// The normal p8g approach would be to assign a draw function to
// the p8g object, but because it's imported through skypack
// at runtime the p8g module is read-only. So instead we use
// this workaround. As a bonus, we can write the draw() function
// as a named cell.
p8g_readonly_workaround = {
await p8g;
// Draw Loop
let request = requestAnimationFrame(function tick() {
draw();
request = requestAnimationFrame(tick);
});

invalidation.then(() => cancelAnimationFrame(request));
}
Insert cell
p8g = await import('https://cdn.skypack.dev/p8g.js@0.8.1?min');
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more