Public
Edited
Oct 14, 2022
2 stars
Insert cell
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

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
canv = createCanvas(W, W)
Insert cell
W=720
Insert cell
function draw(){
const {
stroke, noFill, smooth,
colorMode,
HSB,
line,
background,
strokeWeight

} = p8g;

const {PI, abs, max} = Math;
const TAU = 2 * PI;
let N,F = 0
noFill()
smooth()
mutable t+=.01
background(255)
colorMode(HSB)

strokeWeight(3)
for(let x=72;x<W;x+=144){
for(let y=0;y<W;y+=2) {
(N=(noise1(noise(y/50-t,t)))*150)+(N=(F=(x-72)%288==0)?N:max(120-N,0))
stroke(abs(y/2+F*180-t*99*(F*2-1))%360,99-hundy(N),hundy(N))
line(x-N,y,x+N,y)

}
}
}

Insert cell
Insert cell
hundy = d3.scaleLinear()
.domain([0, 120])
.range([10, 100])
Insert cell
noise1 = d3.scaleLinear()
.domain([-1, 1])
.range([0, 1])
Insert cell
Insert cell
import {perlin2 as noise} from "@mbostock/perlin-noise"
Insert cell
mutable t = 0
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 setup() and draw()
// as top-level named cells.
p8g_readonly_workaround = {
await p8g;
// canv
// Draw Loop
let request = requestAnimationFrame(function tick() {
draw();
request = requestAnimationFrame(tick);
});

invalidation.then(() => cancelAnimationFrame(request));
}
Insert cell
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