Search code examples
javascriptcsstransformpixelimpress.js

Width/Height in pixels for far away transformed elements


I'm currently working on an interface for the web which uses 3D-transforms as a method for zooming. The zooming is done with an API called impress.js which simply put moves a camera closer or further away with 3D-transforms.

Problem

I need to create a square overlay for a bunch of divs and because they can be far away I need to calculate the amount of pixels they actually take up on the screen. I figured that since I can get how many pixels from the div that the camera currently is, I should be able to determine the apparent pixel size of the far away elements.

I have tried estimating it with angular sizes, looking at here. However it does not work when you move too close, too far or an object is too thin or wide.

Code

What I currently do looks something like this:

    var div = $("#target"),
        camera = $("#camera"),

        angularSize = camera.z < 0 ? Math.tan(div.offsetWidth / camera.z) : 1;

    return {
             width: div.offsetWidth * angularSize,
             height: div.offsetHeight * angularSize,
           }

But it only works for certain elements, and not perfectly either.

What I Have:

  • Actual width/height of each element
  • The amount of pixels in Z-index that I am looking at my elements from.

What I need

  • Amount of pixels the far-away elements actually take up on my screen.

If someone knows how I can calculate this I would love some help


Solution

  • Never mind, I realised that I overcomplicated things, and could just use the camera's normal view distance and its current position.

    The camera's perspective before any movement was 1000px and I could get the camera's current z-position any time so I did this:

        sizeScale = 1000 / camera.z;
        return {
                   width: element.offsetWidth * sizeScale,
                   height: element.offsetHeight * sizeScale,
               }