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.
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 / azwhere:axis the original distance from the transform origin pointazis the perspective + the negativetranslateZbzis the perspectiveand this will give you:
bx– the new distance from the transform origin pointSo, you need to know:
bz: theperspective(eg:1000px)ax: the offset from the transform origin point, eg: if the origin point is 50% then this needs to be the element’stoprelative to the center of the parent element (parent.height/2 + element.top) — let’s say-500pxz: the element’stranslateZ(eg:-600px)azis thenbz + z * -1, in this case:1000 + (-600 * -1) = 1600so the formula is:
-500 * 1000 / 1600 = -312.5The element is offset vertically
-312.5pxfrom the origin, whereas originally it was offset-500px, the difference between the two number is what you’ll need to add to the oldtopvalue 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/