Public
Edited
Aug 31, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
canvasContext = {
const context = DOM.context2d(width, height);
const canvas = context.canvas;

let circles = d3.range(number_of_circles).map((i) => ({
x: Math.random() * (width - radius * 2) + radius,
y: Math.random() * (height - radius * 2) + radius,
weight: Math.random() * radius * 2 + 10,
color: colors[i % 10]
}));

let seed = seededRandom(randomSeeds);

let simulation = d3
.forceSimulation(circles)
.force("center", d3.forceCenter(width / 2, height / 2))
// .force("collision", d3.forceCollide().radius(radius))
// .force("center", forceBoundary(20, 20, width - 20, height - 20).border(0))

.on("tick", render);

context.clearRect(0, 0, width, height);
// Set up to compute a Delaunay triangulation from the circles
function render() {
context.clearRect(0, 0, width, height);
// const voronoi = d3.Delaunay.from(
// circles,
// (d) => d.x,
// (d) => d.y
// ).voronoi([0, 0, width, height]);

// .clip([
// [0, 0],
// [0, height],
// [width, height],
// [width, 0]
// ])
let sim = d3
.voronoiMapSimulation(circles)
// .size([width / 2, height / 2])
.weight((d) => d.weight)
.prng(seed)
.clip(ellipse)
.convergenceRatio(0.05)
.maxIterationCount(7)
.initialPosition(d3.voronoiMapInitialPositionPie())
.stop();
let state = sim.state();
let polygons = state.polygons;
while (!state.ended) {
// manually launch each iteration until the simulation ends
sim.tick();
state = sim.state();
}
polygons = state.polygons;
// Draw the voronoi mesh
polygons.forEach((points, i) => {
context.beginPath();
points.forEach((point) => {
context.lineTo(point[0], point[1]);
});
context.fillStyle = colors[i];
context.fill();
});

polygons.forEach((points) => {
context.beginPath();
points.forEach((point) => {
context.lineTo(point[0], point[1]);
});
context.strokeStyle = "rgba(255,255,255,0.2)";
context.lineWidth = 1;
context.stroke();
});
}

const dragBehavior = drag(simulation, circles);

// d3.select(canvas).call(dragBehavior);

render();
return canvas;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@7", "d3-voronoi-map")
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