Prasanna
Prasanna

Reputation: 4636

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 .

Upvotes: 2

Views: 638

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

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 to make clear that it's different from zoom(), but the most traditional name is zoom (of course, you can 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);

Upvotes: 4

Related Questions