Utilizing getBoundingClientRect is a solid method, however the challenge lies in the fact that applying a CSS left property positions an element without taking into account any rotation calculations. The sequence in which you apply styles does not alter the fact that the rotation is applied relative to the CSS properties, rather than the current position of the rotated element. Therefore, when obtaining dimensions using getBoundingClientRect, you are considering the rotation, yet implementing it on CSS that disregards this factor.
An effective technique to obtain accurate coordinates involves calculating the difference in x values before and after rotation, adjusting the left positioning accordingly. By subtracting the previous dimension's x value from the current dimension's x value (prevDimension.x - dimension.x
), you can determine the x difference resulting from the rotation, enabling you to modify newLeft.
For example:
$('#rotate-align').click(function () {
var prevDimensions = $('.element')[0].getBoundingClientRect();
$('.element').css('transform', 'rotate(0.99923rad)');
var dimensions = $('.element')[0].getBoundingClientRect();
var newLeft = $('#bounds').width() - dimensions.width - dimensions.x + prevDimensions.x;
$('.element').css('left', newLeft);
});
Sample Link
Another strategy involves determining the x difference based on the disparity in width between the non-rotated element and the rotated one. This calculation utilizes offsetWidth (which ignores rotation) in conjunction with getBoundingClientRect. The difference obtained highlights the amount of width lost due to rotation. It is crucial to consider the transform origin for this computation; for instance, in a centered rotation, halving the width difference provides the x difference, while a different origin would yield an alternative result.
Like so:
$('#rotate-align').click(function () {
$('.element').css('transform', 'rotate(0.99923rad)');
var dimensions = $('.element')[0].getBoundingClientRect();
var newLeft = $('#bounds').width() - $('.element')[0].offsetWidth + (($('.element')[0].offsetWidth - dimensions.width) / 2);
$('.element').css('left', newLeft);
});
Alternate Example