Search code examples
cssmatrixcss-transformswebkit-perspective

calculate transition distance to justify projection size


I have an image that visually should become bigger by applying z translate with some perspective. I need to calculate translate distance in z direction dist which will result in size increasing of the initial image projection by some factor.


Solution

  • The perspective property sets the distance from the viewer to the scene; that is the same that saying the distance from the viewer to the initial (untransformed) element.

    When you apply a transform, that changes this position, so that the final distance of the element will get decreased in this amount.

    The aparent size of the element will be proportional to this change

    initial distance = perspective

    final distance = perspective - translate-z

    ratio = initial / final

    If the perspective is 1000px, and translateZ is 750px, this will result in a final distance of 250px, and a ratio of 4. The image will get a zoom effect of 4x

    The inverse calculus is:

    translateZ = perspective * (1 - factor)

    example achieving a factor of 4 with perspective 1000px and translate 750px

    .base {
      width: 100px;
      height: 100px;
      perspective: 1000px;
      perspective-origin: -3px -2px;
      border: solid 1px red;
    }
    .transform {
      width: 25px;
      height: 25px;
      border: solid 1px blue;
      transform: translateZ(750px);
      left: 34px;
      top: 34px;
    }
    <div class="base">
    <div class="transform"></div>
    </div>