🏠 back to Observable

D3 zoom


#1

I am trying to fine tune the zoom behavior for a graph and notice something curious.

Here is the code:

var zoom = d3.zoom() .scaleExtent([1 / 2, 2]) .on("zoom", function() { var duration = 250; if (d3.event.sourceEvent.type == "mousemove") { duration = 0; } g.transition().duration(duration).attr("transform", d3.event.transform); });

svg.call(zoom)
.on(“dblclick.zoom”, function() {
svg.call(zoom.transform, d3.zoomIdentity);
});

Apologies for the difficult to read formatting. I wanted to override the double click behavior so that it resets the graph to the original transform.

What’s odd is that for the d3.zoom function I set the g node to have the transform (note that g is the direct child of the svg element where I’m putting all of my graph elements). Where as in the “dblclick” handler I am calling the zoom.transform function on the svg element. When I inspect the page though, both cases are actually modifying the transform of the g node.

Can someone explain what’s going on? I’m having trouble grasping exactly how the zoom mechanics work and while the zooming behavior is behaving as I want it to I’d like to know why it’s doing what it’s doing.


#2

For reference, I am using Edge if it’s possible that’s one of the issues.


#3

Wait, I think I might understand. It looks like by calling zoom.transform execution actually ends up in the listener function I attached to the zoom object. Is it the case that calling zoom.transform actually emulates zoom/transform events via the zoom object?

Still curious if anyone has more insight on the behavior of a zoom function/object though.


#4

Hi - any chance you can link to a notebook, so we can see a full example of the code & behavior?


#5

Definitely, I should’ve done that earlier:

You can find the zooming code in question in the last few lines of the code for each graph (percentPopulationChange and factorOfGrowth)