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



// 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]);

// Draw the voronoi mesh
context.strokeStyle = "#ccc";
context.lineWidth = 1;
context.beginPath();
voronoi.render(context);
context.stroke();
// Draw the circles
for (const { x, y, color, active } of circles) {
context.beginPath();
context.moveTo(x + radius, y);
context.arc(x, y, radius, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
if (active) {
context.strokeStyle = "black";
context.lineWidth = 1;
context.stroke();
}
}
}
d3.select(canvas).call(
drag().on("start.render drag.render end.render", render)
);
render();
return canvas;
}
Insert cell
function drag(first) {
// Find the circle that is closest to my mouse
function dragSubject(event) {
// must be re-initialized again whenever drag happens, because dragging changes the original data
const quadCircles = d3
.quadtree()
.x((d) => d.x)
.y((d) => d.y)
.addAll(circles);
return quadCircles.find(event.x, event.y, Infinity);
}

// raise the chosen subject

function dragStart({ subject }) {
// delete the subject from the original array
circles.splice(circles.indexOf(subject), 1); // remove 1 item starting from the ith item
// add it to the end of the array
circles.push(subject);

subject.active = true;
}

// move the circles
function drag(event) {
event.subject.x = event.x;
event.subject.y = event.y;
}

// change the style of the dragged circle back to normal
function dragEnd({ subject }) {
subject.active = false;
}
return d3
.drag()
.subject(dragSubject)
.on("start", dragStart)
.on("drag", drag)
.on("end", dragEnd);
}
Insert cell
Insert cell
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