Skip to content

Instantly share code, notes, and snippets.

@nicmcd
Last active June 6, 2018 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicmcd/a74b0bfba61f50d932dedd6534ad7d9e to your computer and use it in GitHub Desktop.
Save nicmcd/a74b0bfba61f50d932dedd6534ad7d9e to your computer and use it in GitHub Desktop.
D3 zoom problem

I can't figure out if d3.zoom has a bug or if I'm improperly using it.

I want to have the zooming feature AND a zoom reset feature. Try the following steps:

  1. Drag the box to another location using the mouse
  2. Press SHIRT+R to reset the zoom
  3. Drag the box again using the mouse

What you'll notice is that on step #3, the box will continue dragging as if step #2 never occurred. The same problem exists for all the zoom types such as mouse wheel for zooming in and out. Any zoom event that occurs after the reset acts as if the reset never happened.

What am I missing?

<!DOCTYPE html>
<html>
<head>
<style>
body, html {
width: 100%;
height: 100%;
margin: 0;
}
svg {
position: absolute;
top: 0;
left: 0;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v5.js"></script>
<script type="text/javascript">
function load() {
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%");
var zoom = d3.zoom().on("zoom", function() {
d3.select("#vis").attr("transform", d3.event.transform);
});
var vis = svg.call(zoom).append("g").attr("id", "vis");
d3.select("body").on("keypress", function() {
if (d3.event.shiftKey) {
if (d3.event.key == "R") {
vis.transition().duration(500).attr("transform", d3.zoomIdentity);
}
}
});
vis.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100);
}
</script>
</head>
<body onload="load()">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment