Seeking to obtain the XY coordinates of an HTML element in order to accurately calculate the physical distance, in pixels, from the corners of a rotated element relative to another element.
In this code snippet, I am attempting to determine the distance from the top-left corner of the inner div to the center of the outer div. However, I only have access to the Left and Top values of a non-rotated div. Is there a way to retrieve these coordinates for the rotated div, either in relation to the viewport or another element?
I have experimented with using getBoundingClientRect()
, but it provides a larger rectangle and incorrect coordinates as it encompasses the complete rotated div vertically.
Therefore, I am seeking guidance on how to accurately retrieve these coordinates.
document.getElementById('outRotated').innerHTML = clacDistancCornerCenter() + " Rotated distance of corner to center: "
function clacDistancCornerCenter() {
var outer = document.getElementById('outer');
var inner = document.getElementById('inner');
var centerX = outer.offsetWidth / 2;
var centerY = outer.offsetHeight / 2;
var innersCornerX = outer.offsetLeft;
var innersCornerY = outer.offsetTop;
//distance formula -> d = sqrt( pow( x2 - x1) + pow( y2 - y1) )
var distance = Math.sqrt(Math.pow(centerX - innersCornerX, 2) + Math.pow(centerY - innersCornerY, 2));
return distance;
}
function calcDistHorizontal() {
$('div').css('transform', 'rotate(0deg)');
document.getElementById('outHorizontal').innerHTML = clacDistancCornerCenter()+ " This Should be differnt when horizontal: ";
}
div {
top: 15%;
left: 20%;
width: 50%;
height: 50%;
border: 1px solid black;
position: absolute;
display: block;
transform: rotate(25deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="outRotated"> </p>
<p id="outHorizontal"> </p>
<button onclick="calcDistHorizontal()">Distance Horizontal</button>
<div id="outer">
<div id="mid">
<div id="inner">
</div>
</div>
</div>