简体   繁体   中英

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM