Published unlisted
Edited
Jun 17, 2020
Fork of Drag & Zoom
Insert cell
Insert cell
mutable debug = null
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

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

g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", ({ x }) => x)
.attr("cy", ({ y }) => y)
.attr("r", radius)
.attr("fill", (d, i) => d3.interpolateRainbow(i / 360))
.call(
d3
.zoom()
.scaleExtent([1, 1])
.on("start", dragstarted)
.on("zoom", dragged)
.on("end", dragended)
);

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

function defaultSubject(event, d, that) {
const p = d3.pointer(event.sourceEvent, that.parentElement);
return d == null ? { x: p[0], y: p[1] } : d;
}

let subject, dx, dy;
function dragstarted(event, d) {
const p = d3.pointer(event.sourceEvent, this.parentElement);
subject = defaultSubject(event, d, this);
dx = subject.x - p[0] || 0;
dy = subject.y - p[1] || 0;

console.log("dragstart", { dx, dy, p, event, d });

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

function dragged(event, d) {
const p = d3.pointer(event.sourceEvent, this.parentElement);
event.x = dx + p[0];
event.y = dy + p[1];

console.log("dragged", { dx, dy, p, x: event.x, y: event.y, event, d });

d3.select(this)
.attr("cx", (d.x = event.x))
.attr("cy", (d.y = event.y));
}

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

function zoomed(event) {
g.attr("transform", event.transform);
}

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 {
x: width / 2 + radius * Math.cos(a),
y: height / 2 + radius * Math.sin(a)
};
})
Insert cell
theta = Math.PI * (3 - Math.sqrt(5))
Insert cell
d3 = require.alias({
"d3-drag": "https://d3-two.fil.now.sh/d3-drag.js",
"d3-zoom": "https://d3-two.fil.now.sh/d3-zoom.js",
"d3-selection": "d3-selection@2.0.0-rc.2"
})("d3-array", "d3-scale-chromatic", "d3-drag", "d3-selection", "d3-zoom")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more