Published
Edited
Feb 6, 2020
Fork of Drag & Zoom
2 stars
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

const g = svg.append("g").attr("cursor", "grab");

const circle = g
.selectAll("circle")
.data(data)
.join("circle")
.attr("transform", d => `translate(${d})`)
.attr("r", radius)
.attr("fill", (d, i) => d3.interpolateRainbow(i / 360))
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);

svg.call(
d3
.zoom()
.extent([[0, 0], [width, height]])
.scaleExtent([1 / 8, 8])
.on("zoom", zoomed)
);

function dragstarted() {
d3.select(this).raise();
g.attr("cursor", "grabbing");
}

function dragged(d) {
const transform = d3.zoomTransform(svg.node());
const [x, y] = transform.invert([d3.event.x, d3.event.y]);
d[0] = x;
d[1] = y;
d3.select(this).attr("transform", `translate(${transform.apply(d)})`);
}

function dragended() {
g.attr("cursor", "grab");
}

function zoomed() {
const { transform } = d3.event;
circle.attr("transform", d => `translate(${transform.apply(d)})`);
}

return svg.node();
}
Insert cell
height = 500
Insert cell
radius = 6
Insert cell
step = radius * 2
Insert cell
data = Array.from({ length: 2000 }, (_, i) => {
const radius = step * Math.sqrt((i += 0.5)),
a = theta * i;
return [width / 2 + radius * Math.cos(a), height / 2 + radius * Math.sin(a)];
})
Insert cell
theta = Math.PI * (3 - Math.sqrt(5))
Insert cell
d3 = require("d3@5")
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