I would like to know how can i get the original dimensions of a element after rotating it, when i use transform: rotate()
and try to get the dimensions after rotate using element.getBoundingClientRect()
it returns a different width and heigh, is it possible to get the real dimensions after rotating a element?
let div1 = document.getElementById('one')
let div2 = document.getElementById('two')
// Here the width and height is 50 and 80
console.log(div1.getBoundingClientRect())
// Here because i used transform rotate the width is 86 and height 94
console.log(div2.getBoundingClientRect())
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}
<div id="one"></div>
<br/>
<div id="two"></div>
One option would be to clone the second div with cloneNode
and then remove the tranform
style to get it's original dimensions, please see snippet.
let div1 = document.getElementById('one');
let div2 = document.getElementById('two');
//clone the rotated div and then remove the transform style
//this will give you it's original dimensions
let div3 = div2.cloneNode(false);
div3.style.transform = "none";
//hide the clone
div3.style.visibility = "hidden";
//append to the body
document.body.append(div3);
console.log(div3.getBoundingClientRect());
//remove clone from the DOM
div3.remove();
// Here the width and height is 50 and 80
console.log(div1.getBoundingClientRect());
// Here because i used transform rotate the width is 86 and height 94
console.log(div2.getBoundingClientRect());
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}
<div id="one"></div>
<br/>
<div id="two"></div>
You can use offsetWidth
and offsetHeight
. This is likely more efficient than cloning and modifying the element.
let div1 = document.getElementById('one')
let div2 = document.getElementById('two')
// Here the width and height is 50 and 80
console.log(div1.getBoundingClientRect())
// Here because i used transform rotate the width is 86 and height 94
console.log(div2.getBoundingClientRect())
console.log(div2.offsetWidth);
console.log(div2.offsetHeight);
div#one {
width: 50px;
height: 80px;
background-color: red;
}
div#two {
width: 50px;
height: 80px;
background-color: red;
transform: rotate(35deg);
}
<div id="one"></div>
<br/>
<div id="two"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With