Public
Edited
Mar 2, 2023
Insert cell
Insert cell
Insert cell
{
const height = 700,
context = DOM.context2d(width, height),
canvas = context.canvas,
radius = 20;

var circles = d3.range(324).map(function (i) {
return {
x: (i % 25) * (radius + 1) * 2,
y: Math.floor(i / 25) * (radius + 1) * 2,
type: "#16c444"
};
});

var simulation = d3
.forceSimulation(circles)
.force("collide", d3.forceCollide(radius + 1).iterations(4))
.on("tick", drawCircles);

d3.select(canvas).call(
d3
.drag()
.subject(subject)
.on("start", started)
.on("drag", dragged)
.on("end", ended)
.filter((event) => !viewof lock.value || event.shiftKey)
.touchable(true)
);

return canvas;

function drawCircles() {
context.clearRect(0, 0, width, height);
context.save();

context.fillStyle = "white";
context.arc(0, 0, 1000, 0, 2 * Math.PI, true);
context.fill();
context.closePath();

circles.forEach(drawCircle);
context.strokeStyle = "#ffffff";
context.stroke();
}

function drawCircle(d) {
context.beginPath();
context.fillStyle = d.type;
context.moveTo(d.x + radius, d.y);
context.arc(d.x, d.y, radius, 0, 2 * Math.PI);
context.fill();
}

function subject(event) {
const subject = simulation.find(event.x, event.y, radius);
return subject.type === "#16c444" ? subject : null;
}

function started(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}

function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}

function ended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
}
Insert cell
width = 400
Insert cell
d3 = require.alias({
"d3-drag": "https://d3-two.fil.now.sh/d3-drag.js",
"d3-selection": "d3-selection@2.0.0-rc.2"
})("d3-array", "d3-drag", "d3-force", "d3-selection")
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