Initial zoom not working in d3 v4

旧城冷巷雨未停 提交于 2020-01-24 16:15:09

问题


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 .


回答1:


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);


来源:https://stackoverflow.com/questions/50367145/initial-zoom-not-working-in-d3-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!