Skip to content

Instantly share code, notes, and snippets.

Last active April 23, 2023 04:45
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Pan & Zoom III
license: gpl-3.0

This example demonstrates using d3-zoom to pan and zoom an SVG element by applying an SVG transform using transform.toString. The zoom behavior is applied to an invisible rect overlaying the SVG element; this ensures that it receives input, and that the pointer coordinates are not affected by the zoom behavior’s transform.

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src=""></script>
var svg ="svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var points = d3.range(2000).map(phyllotaxis(10));
var g = svg.append("g");
.attr("cx", function(d) { return d[0]; })
.attr("cy", function(d) { return d[1]; })
.attr("r", 2.5);
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));
function zoomed() {
g.attr("transform", d3.event.transform);
function phyllotaxis(radius) {
var theta = Math.PI * (3 - Math.sqrt(5));
return function(i) {
var r = radius * Math.sqrt(i), a = theta * i;
return [
width / 2 + r * Math.cos(a),
height / 2 + r * Math.sin(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment