Gtb
Gtb

Reputation: 41

d3 zoom listener does not take into account programmatic zoom

Before all, I can make the zoom behaviour work when attached to a "zoom" event (with the mouse for example). AND I can programmatically zoom (triggered by an update in a document for example).

But if I have a zoom event, -->THEN programmatic zoom<--, then zoom event again, the second zoom event restarts from the position of the SVG drawing at the end of the previous mouse "zoom" event.

It is annoyingly discarding what happened during the programmatic zoom.

"zoom" event:

const zoomed = () => select("g").attr("transform", event.transform);

svg
  .call(
    zoom()
      .extent([[0, 0], [600, 600]])
      .scaleExtent([0.1, 5000])
      .clickDistance(10)
      .on("zoom", zoomed)
  )

programmatic zoom:

let transform = zoomTransform(select("g").node());
let t = zoomIdentity
  .translate(transform.x + 1000, transform.y + 1000)
  .scale(transform.k);
select("g").attr("transform", t);

Help much appreciated

Upvotes: 0

Views: 65

Answers (1)

frankenapps
frankenapps

Reputation: 8231

You need to call the transform on your zoom function, like so

svg.transition().duration(300).call(zoomFunc.transform, d3.zoomIdentity.translate(0, 0).scale(1));

where zoomFunc would be something like that

var zoomFunc = d3.zoom()
    .extent([[0, 0], [600, 600]])
    .scaleExtent([0.1, 5000])
    .on("zoom", zoomed);

svg.call(zoomFunc)

I also made a demo JSFiddle.

Upvotes: 1

Related Questions