Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

css - perspective and translateZ moves diagonally

Reference this link: https://developer.mozilla.org/en-US/docs/Web/CSS/perspective

Perspective must be set to move a child element along the z-axis. The link above show examples of different perspective values, all of which set the z-axis in a diagonal direction.

If I'm looking directly at the face of a 3D cube and I move it backwards (along the z-axis) it would look like it's getting smaller (moving away from me), not moving diagonally. So why does CSS have a diagonal z-axis by default? Is there a way to use perspective and translateZ with a z-axis that moves exactly away from the user?

Some code I've been testing this with:

.wrapper {
  position: relative;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
  perspective: 1px;
  transform-style: preserve-3d;
}

.cube {
  transform-origin: 50% 50%;
  transform: translateZ(-1px);
}

<div class="wrapper">
  <div class="cube"></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's all a matter of perspective-origin that define how the changes should be visible to us.

If you read the same link you will notice this:

The vanishing point is by default placed at the center of the element, but its position can be changed using the perspective-origin property.

Here is some example where you can better understand:

.wrapper {
  position: relative;
  height: 100px;
  width: 100px;
  border: 1px solid;
  perspective: 10px;
  transform-style: preserve-3d;
}

.cube {
  width: 100%;
  height: 100%;
  background: red;
  animation: change 2s linear infinite alternate;
}

@keyframes change {
  to {
    transform: translateZ(-10px);
  }
}
moving from the center
<div class="wrapper">
  <div class="cube"></div>
</div>
moving from the left
<div class="wrapper" style="perspective-origin:left">
  <div class="cube"></div>
</div>
moving from a custom point
<div class="wrapper" style="perspective-origin:20% 80%">
  <div class="cube"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...