站点工具

用户工具


盒子

立方体对象很容易生成,因为我们只需要担心一个度量。但是我们将如何处理一个不规则的直角立方体呢?举个例子,让我们尝试制作一个 300px 宽、200px 高和 100px 深的盒子。

HTML结构依旧保持不变。

<div class="scene">
  <div class="box">
    <div class="box__face box__face--front">front</div>
    <div class="box__face box__face--back">back</div>
    <div class="box__face box__face--right">right</div>
    <div class="box__face box__face--left">left</div>
    <div class="box__face box__face--top">top</div>
    <div class="box__face box__face--bottom">bottom</div>
  </div>
</div>

同为立方体,但宽高和深度改变, width: 300pxheight: 200px,因.box深度是100px,所以设置translateZ(-50px)

.scene {
  width: 300px;
  height: 200px;
  perspective: 500px;
}

.box {
  width: 300px;
  height: 200px;
  position: relative;
  transform-style: preserve-3d;
  transform: translateZ(-50px);
}

.box__face--front,
.box__face--back {
  width: 300px;
  height: 200px;
}

.box__face--right,
.box__face--left {
  width: 100px;
  height: 200px;
}

.box__face--top,
.box__face--bottom {
  width: 300px;
  height: 100px;
}

设置position: absolute到各个面,让各个面都在.box左上角重叠。

为了在 3D 中从盒子的中心平移出面,我们需要将面居中。我们可以通过添加topleft定位样式来做到这一点。.box__face--left.box__face--right需要设置定位left: 100px.box__face--top.box__face--bottom需要设置定位top: 50px

.box__face--right,
.box__face--left {
  width: 100px;
  height: 200px;
  left: 100px;
}
 
.box__face--top,
.box__face--bottom {
  width: 300px;
  height: 100px;
  top: 50px;
}

要在 3D 中定位各个面,旋转值可以保持之前的立方体示例相同,但对于当前这个长方体,平移值是不同怼。由于长方体的深度为 100 像素,因此正面和背面都向外移动50px。长方体的宽度 300px,所以左右面各自平移150px。长方体的高度为 200 像素,所以顶部和底部面各自平移100px。

.box__face--front  { transform: rotateY(  0deg) translateZ( 50px); }
.box__face--back   { transform: rotateY(180deg) translateZ( 50px); }
 
.box__face--right  { transform: rotateY( 90deg) translateZ(150px); }
.box__face--left   { transform: rotateY(-90deg) translateZ(150px); }
 
.box__face--top    { transform: rotateX( 90deg) translateZ(100px); }
.box__face--bottom { transform: rotateX(-90deg) translateZ(100px); }

就像立方体的例子,要暴露一个面,#box需要有一个样式来反转变换。同时设置translateZrotate值来展示其相对应的面。

.box.show-front  { transform: translateZ( -50px) rotateY(   0deg); }
.box.show-back   { transform: translateZ( -50px) rotateY(-180deg); }
.box.show-right  { transform: translateZ(-150px) rotateY( -90deg); }
.box.show-left   { transform: translateZ(-150px) rotateY(  90deg); }
.box.show-top    { transform: translateZ(-100px) rotateX( -90deg); }
.box.show-bottom { transform: translateZ(-100px) rotateX(  90deg); }

在 CodePen 上编辑此演示

若愚 · 2021/12/21 15:36 · css3d_盒子.1640072216.txt.gz