Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 V4 setting initial zoom level

I've just started using D3 V4 and I'm having trouble getting a pan and zoom function working. The problem is that I want the initial scale value to be something over than 1 so I set this using

zoom.scaleTo(svg, 2);

However as soon as I pan or zoom the scale resets back to 1.

Here's an example of this behavior on JSFiddle, what am I doing wrong?

JSFiddle

like image 913
Connor Avatar asked Jul 14 '16 16:07

Connor


1 Answers

Here's the problem:

var svg = d3.select("body").append("svg")
    .attr("width", 600)
    .attr("height", 600)
  .call(zoom)
  .append("g");

You are assigning the group element instead of the svg element to the variable svg.

The zoom is correctly applied to the svg element, but then when you call zoom.scaleTo(svg, 2) you are zooming the group element, not the svg element.

This can be fixed by first creating and assigning the svg element to the svg variable and only then creating and assigning the group element.

var svg = d3.select("body").append("svg")
    .attr("width", 600)
    .attr("height", 600)
    .call(zoom);

var mainContainer = svg.append("g");

Here's the fixed JSFiddle: https://jsfiddle.net/skgktrcu/2/

like image 64
Ashitaka Avatar answered Sep 22 '22 19:09

Ashitaka