Home > database >  How to calculate distance of between two rectangle corners
How to calculate distance of between two rectangle corners

Time:10-15

I want to calculate the distance between given two DOM elements that pointed corners. I used Math.hypot function for the calculation however there is a mistake while doing it, which slightly overflows the corner instead of the exact point.

function getPositionAtCenter(element) {
   const {top, left, width, height} = element.getBoundingClientRect();
   return {
     x: left   width / 2,
     y: top   height / 2
   };
 }

function getDistanceBetweenElements(a, b) {
  const aPosition = getPositionAtCenter(a);
  const bPosition = getPositionAtCenter(b);

  return Math.hypot(aPosition.x - bPosition.x, aPosition.y - bPosition.y);  
}

enter image description here

CodePudding user response:

Just subtract the left value of the second div from the left value of first div.

let divs = document.querySelectorAll(".div")
let div1Position = divs[0].getBoundingClientRect();
let div2Position = divs[1].getBoundingClientRect();

console.log(div2Position.left - div1Position.left)
<div  style="width:100px; height:100px; background-color:grey; position:absolute; left: 100px; top:0;"></div>

<div  style="width:100px; height:100px; background-color:grey; position:absolute; left:500px; top:0;"></div>

  • Related