I am trying to get a zoom functionality to work with my d3 network (as per here), but am not replicating the behaviour. I first create the zoom variable:
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
Then I create the svg:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.right + ")")
.call(zoom);
Then finally the function itself:
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
However, the network does not allow me to zoom, either by clicking on a node, or from zooming. I attach the full file if this is needed also.
Does anyone know why I am not getting this behaviour?
Best,
Ben
Mistake 1
You are doing:
function zoomed() {
contaner.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
You should be doing
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
Reason the translate/scale should happen to the g DOM(group) which hold the full graph in your case i.e. variable svg
.
Mistake 2:
Append a rectangle to the full length and breadth of SVG to capture the zoom events.
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
Working example here
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With