Can I calculate the size of my transformed element?

Viewed 71

For example, I apply to my element perspective(200px), transform: scale(1.5); and translateZ(100px) properties. So, how can I calculate what size will have my transformed element? Is there any formula?

I think this question is more relevant when we use perspective together with translateZ, because mainly in these situations I don't know for sure how my element will look like.

.green {
  width: 300px;
  height: 300px;
  outline: 1px solid black;
  background: yellowgreen;
  margin: 50px;
  transform-origin: 400px 0px;
  transform: perspective(200px) scale(1.5) translateZ(100px);
}
<div class="green"></div>

1 Answers

I'm not completely clear whether this fulfills your requirements, but it appears that Element.getBoundingClientRect() will return the transformed dimensions of the element:

const elWithTransforms = document.querySelector('#elementWithTransforms');
const elWithoutTransforms = document.querySelector('#elementWithoutTransforms');

const transDimensions = elWithTransforms.getBoundingClientRect();
const noTransDimensions = elWithoutTransforms.getBoundingClientRect();

console.log(`Green element dimensions:\n    width: ${transDimensions.width}\n    height: ${transDimensions.height}`);
console.log(`Purple element dimensions:\n    width: ${noTransDimensions.width}\n    height: ${noTransDimensions.height}`);
.green {
  width: 300px;
  height: 300px;
  outline: 1px solid black;
  background: yellowgreen;
  margin: 50px;
  transform-origin: 400px 0px;
  transform: perspective(200px) scale(1.5) translateZ(100px);
}

.purple {
  width: 300px;
  height: 300px;
  outline: 1px solid black;
  background: purple;
  margin: 50px;
}
<div class="green" id="elementWithTransforms" ></div>
<div class="purple" id="elementWithoutTransforms" ></div>

I wasn't certain if this was something you needed to do ahead of time on paper, or something you could do with JS in the browser. If the latter, this should fulfill your needs.

If it is important that this happen before the element is visible, you have some options. getBoundingClientRect() will return all zeroes if called before the element is attached to the DOM, but you can attach the element to the DOM offscreen/invisible and get the dimensions from getBoundingClientRect(), and then remove the element, do any additional work you need to do, and reattach it after unhiding it.

const body = document.querySelector('body');
const div = document.createElement('div');
div.classList.add('green');
div.classList.add('hideOffScreen');
body.appendChild(div);

console.log(div.getBoundingClientRect());
.green {
  width: 300px;
  height: 300px;
  outline: 1px solid black;
  background: yellowgreen;
  margin: 50px;
  transform-origin: 400px 0px;
  transform: perspective(200px) scale(1.5) translateZ(100px);
}

.hideOffScreen {
  position: absolute;
  left: -9999px;
  z-index: -1;
  visibility: hidden;
}

Related