Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the real width and height of element after rotating it?

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>
like image 735
João Hamerski Avatar asked May 07 '21 20:05

João Hamerski


2 Answers

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>
like image 72
Ryan Wilson Avatar answered Oct 21 '22 04:10

Ryan Wilson


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>
like image 44
Nisala Avatar answered Oct 21 '22 05:10

Nisala