用css3做一個3D立方體


首先看一下效果圖

 

1.坐標系,要在腦海里先建立一個3D坐標系

如下圖,看清楚x,y,z軸

 

2.html代碼。

<div class="container">
<!--包裹六個面的元素--> <div class="cube">
<!--立方體的六個面--> <div class="plane-front">前面</div> <div class="plane-back">后面</div> <div class="plane-left">左面</div> <div class="plane-right">右面</div> <div class="plane-top">上面</div> <div class="plane-bottom">下面</div> </div> </div>

3.css3代碼

/*1.首先給html設置一個背景,順便練習一下漸變*/
html{
background:linear-gradient(#9ed128 0%,#358b98 80%);
opacity: 0.8;
height: 100%;
}

/*2.給。container設置perspective,定義透視效果(元素距離視圖的距離),可以改變值嘗試。perspective:number/none;(none相當於設置為0,不設置透視效果)。
在這里為了視覺體驗更好,設置一下。*/
.container{
margin-top: 200px;
perspective:1000px;
}

/*3.定義最外層包裹六個面的container,並且定義動畫。使其旋轉,然后再定義那六個面的位置,到時候那六個面也會一同旋轉。*/
.cube{
height: 200px;
width: 200px;
position: relative;
margin:auto;
transform-style:preserve-3d;/*定義3d轉換*/
animation:rotate 15s infinite;/*animation:動畫名字 時長 無限循環 線性速度(勻速)*/
}
/*動畫效果,也可以以百分百的方式。默認逆時針的方向旋轉。*/
@keyframes rotate{
from{
transfrom:rotateY(0deg) rotateX(0deg);
}
to{
transform: rotateY(360deg) rotateX(360deg);
}
}

/*4.定義每一個面的寬高、行高等內容*/
.cube>div{
height: 100%;
width: 100%;
opacity: 0.9;
position: absolute;
text-align: center;
background: #333;
color:#fff;
line-height: 200px;
font-size: 30px;
border:1px solid #fff;
}

/*5.根據坐標系對每一個面進行定位、旋轉得到立方體*/
/* transform:向元素應用3D轉換。
translateX/translateY/translateZ:定義3D轉換,此函數用來規定指定元素在三維空間中的位移。
rotateX/rotateY/rotateZ:定義旋轉。
推薦:http://fangyexu.com/tool-CSS3Inspector.html。
*/
.plane-front{
transform:translateZ(100px);
}
.plane-back{
transform:translateZ(-100px);
}
.plane-left{
transform:rotateY(90deg) translateZ(-100px);
}
.plane-right{
transform:rotateY(90deg) translateZ(100px);
}
.plane-top{
transform:rotateX(90deg) translateZ(100px);
}
.plane-bottom{
transform:rotateX(90deg) translateZ(-100px);
}

/*5.設置鼠標滑過的樣式,讓每一個面向外走100px*/
.cube:hover .plane-front{
transform:translateZ(200px);
}
.cube:hover .plane-back{
transform:translateZ(-200px);
}
.cube:hover .plane-left{
transform:rotateY(90deg) translateZ(-200px);
}
.cube:hover .plane-right{
transform:rotateY(90deg) translateZ(200px);
}
.cube:hover .plane-top{
transform:rotateX(90deg) translateZ(200px);
}
.cube:hover .plane-bottom{
transform:rotateX(90deg) translateZ(-200px);
}
/*如果要考慮兼容,需要給animation、transform等加前綴。*/

於是一個會動的立方體就大功告成了~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM