3

I would like to do the following: Given a container with perspective and an inner element with a translateZ value I'd like to "pull it up" with translateY in order to visually touch the top of the surrounding container: http://jsfiddle.net/8R4ym/129/

Is there some kind of formula that, given the perspective value of a container, the width and height of an element and it's Z-translation I can get to that kind of "top" calculation? I have been playing around with it but I can't seem to find some rules for it, as it seems that those are all variables.

Thanks for any help.

Seka
  • 1,413
  • 2
  • 12
  • 16

2 Answers2

8

Yes!

There's actually quite a simple formula for finding the offset - the 3d Projection article on Wikipedia has a diagram and the formula.

The formula is bx = ax * bz / az where:

  • ax is the original distance from the transform origin point
  • az is the perspective + the negative translateZ
  • bz is the perspective

and this will give you:

  • bx - the new distance from the transform origin point

So, you need to know:

  • bz : the perspective (eg: 1000px)
  • ax : the offset from the transform origin point, eg: if the origin point is 50% then this needs to be the element's top relative to the center of the parent element (parent.height/2 + element.top) -- let's say -500px
  • z : the element's translateZ (eg: -600px)
  • az is then bz + z * -1, in this case: 1000 + (-600 * -1) = 1600

so the formula is: -500 * 1000 / 1600 = -312.5

The element is offset vertically -312.5px from the origin, whereas originally it was offset -500px, the difference between the two number is what you'll need to add to the old top value to get the equivalent new value.

This formula also works for the Y axis.

I put together a quick example here: http://jsfiddle.net/trolleymusic/xYRgx/

Trolleymusic
  • 2,162
  • 3
  • 19
  • 26
  • Oh, and the example is -webkit prefixed - sorry. – Trolleymusic Oct 05 '12 at 12:54
  • 1
    I was working on this myself and created the following pen if anyone is interested: http://codepen.io/aaron/pen/lvrba – Aaron Feb 14 '13 at 18:53
  • @Trolleymusic maybe you are the one who knows [the formular i'm looking for](https://stackoverflow.com/questions/45578101/formular-to-calculate-width-height-relative-to-parent-of-container-with-transl). I really hope so (+100 bounty available)! – Axel Aug 19 '17 at 14:15
0

There might be (don't know offhand) but have you tried changing -webkit-transform-origin:; first to see if you can simply apply the transformation along the top so the element appears where you want it without translating it?

David Millar
  • 1,858
  • 1
  • 14
  • 23
  • I tried that but I guess it does not affect anything because it's translating into the z-axis... – Seka May 08 '12 at 19:00