Question

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.

Was it helpful?

Solution

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/

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top