Published
Edited
Aug 6, 2018
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
// if offscreen canvas works in your browser (see https://beta.observablehq.com/@fil/hello-offscreen-canvas),
// you might try and push this number up to 300000 or more…
n = 10000
Insert cell
{
if (offscreen) {
yield md`# 🤞 Using offscreen canvas`;
Generators.queue(worker(draw, { canvas:offscreen, n, width, height }, `
importScripts("https://unpkg.com/d3-delaunay");
importScripts("https://unpkg.com/d3-color");
`, [offscreen]));
} else {
yield md`# 😪 Offscreen canvas not available - using direct draw`;
draw({canvas, n, width, height});
}
}
Insert cell
function draw({ canvas, n, width, height }) {
const context = canvas.getContext("2d");

context.fillText(`Computing ${n} points…`, 20, 20);

var points = new Float32Array(2 * n).map(
i => Math.random() * (i % 2 ? height : width)
);
const fills = [];
for (let i = 0; i < 360; i++) {
fills[i] = d3.hsl(i % 360, 0.9, 0.5);
}

var delaunay, voronoi;
function voro() {
context.fillText(`Computing Voronoi…`, 20, 50);
delaunay = new d3.Delaunay(points);
voronoi = delaunay.voronoi([0, 0, width, height]);
requestAnimationFrame(step);
}

function step() {
(context.fillStyle = "#fff"), context.fillRect(0, 0, width, height);
for (let i = 0; i < n; i++) {
context.beginPath(),
voronoi.renderCell(i, context),
(context.fillStyle = fills[i % 360]),
context.fill();
}

context.beginPath(),
voronoi.render(context),
(context.strokeStyle = "#000"),
(context.lineWidth = 0.5),
context.stroke();
}

requestAnimationFrame(voro);
}
Insert cell
Insert cell
Insert cell
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