Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 zoom not working as in example

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

like image 319
ben18785 Avatar asked Jan 10 '16 01:01

ben18785


1 Answers

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!

like image 67
Cyril Cherian Avatar answered Oct 18 '22 01:10

Cyril Cherian