Can we get a zoom scale with the help of the dimentions(width & height) of the element in js

Viewed 28

Im currently facing the issue with the zoom level in d3.js

I got the dimentions for <g className ="_zoomElement"> element with the help of this function

const g = select("._zoomElement")
      console.log(g.node().getBBox())

I want to fit the group element into the svg Canvus according to the svg dimentions with the help of one button click I got the svg canvus width and height dimentions too

Explanation Image

enter image description here

i dont know how to find the scale value with the help of dimentions

i thought like this

if parent element dimetions would be like this width = 1000px height = 500px

i will reduct 2% from that values we get the fit ratio

but my concern how can we get zoom scale value with that values

1 Answers

finally i found the answer myself by searching on d3.js zoom to fit example then i found solution on this post click to view

function zoomFit(paddingPercent, transitionDuration) {
 var bounds = view.node().getBBox();
var parent = view.node().parentElement;
var fullWidth = parent.clientWidth,
  fullHeight = parent.clientHeight;
var width = bounds.width,
  height = bounds.height;
var midX = bounds.x + width / 2,
  midY = bounds.y + height / 2;
if (width == 0 || height == 0) return; // nothing to fit
var scale =
  (0.79 || 0.75) / Math.max(width / fullWidth, height / fullHeight);
var translate = [
  fullWidth / 2 - scale * midX,
  fullHeight / 2 - scale * midY,
];
svg
  .transition()
  .duration(200 || 0)
  .call(
    zoom.transform,
    d3.zoomIdentity.translate(...translate).scale(scale)
  );

}

end of this code i got translate values and scale this is the perfect code for zoom to fit just attach that fuction to the main group

const root = select("._zoomElement") // main group seletion
  console.log(root.node().getBBox())

everything has worked fine for me

Related