Published
Edited
Oct 12, 2022
1 fork
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
can = createCanvas(W, W)
Insert cell
function draw(){

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

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

t[0]+=.005
let F = 0.5
let X,Y,R = 0

background(128,255,0,9)
translate(360,360)
for(let r=0;r<TAU+(X=Y=0)+!(F=++F%6);r+=PI/18) {
for(let d=0;d<350;d+=3) {
stroke(255*sin(d/(9*sin(d/99-t[0]))-t[0]*99))
line(X,Y,X+=cos(R=r+(p5ed(simplex.noise2D(d/200-t,1))-.5)*9*(F-3))*3,Y+=sin(R)*3)
}
}
}
Insert cell
S = 600 // not 1000 due to p8g issue
Insert cell
W = 720
Insert cell
t=[0]
Insert cell
Insert cell
p5ed = d3.scaleLinear()
.domain([-1, 1])
.range([0, 1])
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();
mutable framecount++;
request = requestAnimationFrame(tick);
});

invalidation.then(() => cancelAnimationFrame(request));
}
Insert cell
mutable framecount = 0
Insert cell
p8g = await import('https://cdn.skypack.dev/p8g.js@0.8.0?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