Connor
Connor

Reputation: 244

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

Upvotes: 6

Views: 6074

Answers (1)

Ashitaka
Ashitaka

Reputation: 19203

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/

Upvotes: 13

Related Questions