Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active August 8, 2019 16:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/3127661b6f13f9316be745e77fdfb084 to your computer and use it in GitHub Desktop.
Drag & Zoom II
license: gpl-3.0
redirect: https://observablehq.com/@d3/drag-zoom

This example shows how to combine d3-drag and d3-zoom to allow dragging of individual circles within a zoomable SVG. If you click and drag on the background, the view pans; if you click and drag on a circle, it moves.

This is quite a bit simpler than implementing drag-and-zoom with Canvas, since the SVG element automatically provides hit-testing, coordinate system transformation and re-rendering.

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
transform = d3.zoomIdentity;;
var points = d3.range(2000).map(phyllotaxis(10));
var g = svg.append("g");
g.selectAll("circle")
.data(points)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 2.5)
.call(d3.drag()
.on("drag", dragged));
svg.call(d3.zoom()
.scaleExtent([1 / 2, 8])
.on("zoom", zoomed));
function zoomed() {
g.attr("transform", d3.event.transform);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function phyllotaxis(radius) {
var theta = Math.PI * (3 - Math.sqrt(5));
return function(i) {
var r = radius * Math.sqrt(i), a = theta * i;
return {
x: width / 2 + r * Math.cos(a),
y: height / 2 + r * Math.sin(a)
};
};
}
</script>
@curran
Copy link

curran commented Jun 18, 2016

It seems like the transform = d3.zoomIdentity; variable is not being used here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment