3D旋轉效果主要使用了CSS3 transform 屬性
首先我們先完善佈局
要想完成一個立方體,首先我們要有一個參考界面,也就是立方體的核心
如圖,標註區域就是我們的核心區,立方體的每個界面都是以核心爲參考系
核心區域只需要一個簡單的平面就可以,記得加上transform-style: preserve-3d;
子元素將保留其 3D 位置。
<body>
<!-- 核心區 -->
<ul class="box">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
.box{
position: absolute;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
transform-style: preserve-3d;
background: #eee;
box-sizing: border-box;
}
接下來將定位六個面位置,爲了方便觀察位置,我們給核心區一個默認旋轉值transform: rotateX(45deg) rotateY(45deg);
然後是根據核心區定位第一個面
<body>
<!-- 核心區 -->
<ul class="box">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
.box{
position: absolute;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
transform-style: preserve-3d;
background: #eee;
box-sizing: border-box;
transform: rotateX(45deg) rotateY(45deg);
}
.box li{
position: absolute;
top: 0;
left: 0;
list-style: none;
width: 200px;
height: 200px;
}
.box li:nth-child(1){
background: #159DE3;
transform: translateX(-100px) rotateY(90deg)
}
translateX(-100px) rotateY(90deg)
的意思是元素沿着X軸移動-100px,沿着 Y 軸的 3D 旋轉90度
同理,與這個面對應的應該是元素沿着X軸移動100px,沿着 Y 軸的 3D 旋轉90度
translateX(100px) rotateY(90deg)
紅色被核心區擋住了一部分,放心不影響
舉一反三,我們將其他界面完成
html,body {width: 100%;height: 100%;}
* {margin: 0;padding: 0;}
.box{
position: absolute;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
transform-style: preserve-3d;
background: #eee;
box-sizing: border-box;
transform: rotateX(45deg) rotateY(45deg);
}
.box li{
position: absolute;
top: 0;
left: 0;
list-style: none;
width: 200px;
height: 200px;
opacity: 0.5;
}
.box li:nth-child(1){
background: #159DE3;
transform: translateX(-100px) rotateY(90deg)
}
.box li:nth-child(2){
background: red;
transform: translateX(100px) rotateY(-90deg)
}
.box li:nth-child(3){
background: orange;
transform: translateZ(100px) rotateY(0deg)
}
.box li:nth-child(4){
background: green;
transform: translateZ(-100px) rotateY(0deg)
}
.box li:nth-child(5){
background: pink;
transform: translateY(-100px) rotateX(90deg);
}
.box li:nth-child(6){
background: blue;
transform: translateY(100px) rotateX(90deg);
}
看上去不太美觀,我們把核心區顏色去掉,核心區只是一個參考系的作用,沒必要顯示出來
哦了,佈局已經完成,接下來讓立方體跟着鼠標旋轉
前面已經說過,所有的面都是根據核心區去定位的,所以旋轉立方體其實就是旋轉核心區
我們已經將核心區的旋轉默認值設置爲transform: rotateX(45deg) rotateY(45deg);
打開控制檯我們來修改旋轉值來看下效果
所以只要修改核心區的旋轉,其他幾個面也會相應的根據核心區做出位置改變
根據鼠標在body上的位置,來等比旋轉立方體
<script>
$('body').mousemove(function(e){
console.log(e.pageX + ", " + e.pageY)
var bWidth=$('body').width()/360;
var bHeight=$('body').height()/360;
var roateY=e.pageX/bWidth;
var roateX=e.pageY/bHeight;
console.log(roateY)
console.log(roateX)
$('.box').css('transform',"rotateX("+roateX+"deg) rotateY("+roateY+"deg)")
});
</script>