简体   繁体   中英

Initial zoom not working in d3 v4

I have imported zoom like this

import {zoom} from 'd3-zoom';

My svg and group container look something like this

const svg = select(root)
      .append('svg')
      .attr('width', width)
      .attr('height', height);

const container = svg.append('g');
const zoomScale = 2;

I tried to set an initial zoom level (via zoom().scaleTo() function like this

zoom().scaleTo(container, zoomScale)

or like this

container.call(zoom().scaleTo, zoomScale)

But nothing is reflected back. Interestingly the zoom function works , which looks like this

svg.call(
  zoom().on('zoom', () => {
    const transformation = getEvent().transform;
    const {x, y, k} = transformation;
    container.attr('transform', `translate(${x}, ${y})scale(${k})`);
  })
);

Adding initial zoom by adding transform in my container works as well, but on the next zoom trigger, zoom starts off with value 1 and a flicker sort of thing is seen in the whole chart. I wish to avoid that.

What is wrong here ? please help .

Set a variable or a constant using the d3.zoom() method (or, in your case, zoom() ):

const myZoom = zoom().on('zoom', () => {
    const transformation = getEvent().transform;
    const {x, y, k} = transformation;
    container.attr('transform', `translate(${x}, ${y})scale(${k})`);
});

Here I'm using myZoom as the name just to make clear that it's different from zoom() , but the most traditional name is zoom (of course, you chan choose whatever valid name you want).

Then, you can use it as:

myZoom.scaleTo(container, zoomScale)

The main difference between using myZoom.scaleTo(container, zoomScale) and zoom().scaleTo(container, zoomScale) is that myZoom holds a reference to the event handlers and other methods in the chain, if any.

Also, don't forget to change the call in the SVG, which becomes just:

svg.call(myZoom);

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