css 3d z轴
In this article, we are going to create a small 3D scene, where the user can scroll on the z-axis. You can find the final code of this tutorial on GitHub, and the demo if you follow this link.
在本文中,我们将创建一个小的3D场景,用户可以在其中在z轴上滚动。 如果您单击此链接,则可以在GitHub上找到本教程的最终代码以及演示。
This article assumes that you already have some knowledge about CSS and JavaScript. We are going to use CSS custom properties, so if you are not familiar with this you can read CSS custom properties — Cheatsheet.
本文假定您已经对CSS和JavaScript有所了解。 我们将使用CSS定制属性,因此,如果您对此不熟悉,则可以阅读CSS定制属性-Cheatsheet 。
CSS 3D简介 (Introduction to CSS 3D)
When speaking of CSS 3D, we’re really speaking about CSS3 transform 3D. This method allows us to use the transform
CSS property to set perspective or rotation on the z-axis to our DOM elements.
当谈到CSS 3D时,我们实际上是在谈论CSS3变换3D。 这种方法允许我们使用transform
CSS属性来设置DOM元素在z轴上的透视图或旋转。
The transform CSS property lets you rotate, scale, skew or translate an element. It modifies the coordinate space of the CSS visual formatting model. transform — MDN
transform CSS属性使您可以旋转,缩放,倾斜或平移元素。 它修改CSS视觉格式模型的坐标空间。 转换-MDN
To be allowed to render our Dom elements in a 3D space we need to have a look at the following properties:
为了允许在3D空间中渲染我们的Dom元素,我们需要查看以下属性:
- Perspective 透视
- Perspective origin 透视图起源
- Transform Z 变换Z
透视 (Perspective)
perspective
is a CSS property that set the distance between z=0 and the user. The smaller is the perspective value, and the greater will be the distortion of our scene. (Try to change the value of scenePerspective
in the codePen example below).
perspective
是一个CSS属性,用于设置z = 0与用户之间的距离。 透视值越小,场景的失真就越大。 (尝试在下面的codePen示例中更改scenePerspective
的值)。
.container-scene { perspective: 100px; }
The value of perspective
is a length unit.
perspective
的值是一个长度单位 。
Try to set the value of scenePerspective
to 0 and 70 in the example below. You can notice that our cube gets no perspective at all if its value is set to 0. If the value is set to 70, you can see a really strong distortion of the cube perspective. The smaller the perspective value is, the deeper it is.
在下面的示例中,尝试将scenePerspective
的值设置为0和70。 您会注意到,如果将其多维数据集的值设置为0,则它根本不会获得任何透视图。如果将该值设置为70,则可以看到多维数据集透视图的失真非常大。 透视值越小,深度越深。
To be able to render a 3D space, we need to specify transform-style: preserve-3d;
on the child elements. In the above example, it set to our .cube
. By default, the elements are flattened.
为了能够渲染3D空间,我们需要指定transform-style: preserve-3d;
在子元素上。 在上面的示例中,它设置为.cube
。 默认情况下,元素被展平。
.container-scene {
perspective: 400px;
}
.container-scene .cube {
transform-style: preserve-3d;
}