Skip to content

Instantly share code, notes, and snippets.

@sgruhier
Last active May 31, 2016 19:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sgruhier/1d692762f8328a2c9957 to your computer and use it in GitHub Desktop.
Save sgruhier/1d692762f8328a2c9957 to your computer and use it in GitHub Desktop.

Simplest way to add pan/zoom to a d3js visualisation

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
<style type="text/css">
body, html {
width: 100%;
height: 100%;
margin: 0;
}
svg {
position: absolute;
top: 0;
left: 0;
}
p {
text-align: center;
}
</style>
</head>
<body>
<p>Use the mouse to pan (click and move) / zoom (scrollwheel)</p>
</body>
<script type="text/javascript">
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.behavior.zoom().on("zoom", function () {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")
}))
.append("g")
svg.append("circle")
.attr("cx", document.body.clientWidth / 2)
.attr("cy", document.body.clientHeight / 2)
.attr("r", 50)
.style("fill", "#B8DEE6")
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment