Getter Jetter
Getter Jetter

Reputation: 2081

d3.js v4 zoom to chart center (NOT MOUSE POSITION!!)

I have one more problem with d3 zooming.

I try to zoom to the center of the graph (ignoring mouse position). But I don't find anything that works for me.

I tried this but i don't get it work.

And didn't found anything in the docs.

Zoom behavior:

//zoom behavior
let zoom = d3.zoom()
  .scaleExtent([0.5, 5])
  .on("zoom", zoomed);

function zoomed() {
  .. some behavior ..
  //center here?
  .. some behavior ..
}

I think this should be an easy thing to do and don't understand, why it's not documented clearly somewhere.

Please see this fiddle for the whole thing.

Help would be greatly appreciated

Upvotes: 2

Views: 1307

Answers (1)

Getter Jetter
Getter Jetter

Reputation: 2081

I managed to solve my issue.

See this fiddle for the details.

Note, that this will disable the x-panning as well.

Here the relevant code:

function getBoundingBoxCenterX (selection) {
  let element = selection.node();
  let bbox = element.getBBox();
  return bbox.x + bbox.width/2;
} 

//zoom behavior
let zoom = d3.zoom()
  .scaleExtent([1, 5])
  .on("zoom", zoomed);

function zoomed() {
  let center = getBoundingBoxCenterX(rect); //rect is the charts parent which expands while zooming
  let chartsWidth = (2 * center) * d3.event.transform.k;
  d3.event.transform.x = center - chartsWidth / 2;

  rescaling operations with d3.event.transform....
}

Upvotes: 2

Related Questions