这是一款使用jquery和CSS3制作的3D旋转立方体特效。该特效使用GSAP来制作动画,通过CSS transform来制作立方体效果兼容除IE之外的其它现代浏览器。
由于IE浏览器不知支持transform-style:preserve3d
,所以在IE中看到的不是立方体效果,而是平面效果。
使用方法
在页面中引入jquery和TweenMax.min.js文件。
<script src='path/to/jquery.min.js'></script> <script src='path/to/TweenMax.min.js'></script>
HTML结构
3D立方体的HTML结构如下:
<div id="trans3DDemo1"> <div id="trans3DBoxes1"> <div>Front</div> <div>Left</div> <div>Right</div> <div>Top</div> <div>Bottom</div> <div>Back</div> </div> </div>
CSS样式
为立方体添加如下的CSS样式:
#trans3DDemo1 { position:relative; display:inline-block; width:250px; height:250px; } #trans3DBoxes1 div { position:absolute; width:248px; height:248px; padding:0; margin:0; background:url(../img/girl.jpg); border:solid 2px #FFF; display:block; text-align:center; font-size:36px; font-weight:bold; }
JavaScript
在页面DOM元素加载完毕之后,通过下面的方法来初始化该立方体效果:
var trans3DDemo1 = $("#trans3DDemo1"), trans3DBoxes1 = $("#trans3DBoxes1"),// div containing all the the boxes boxes1 = $("#trans3DBoxes1 div"), // all the boxes threeDTimeline = new TimelineMax({onUpdate:updateCube, repeat:-1}), stageW = ($(window).width())/2, stageH = ($(window).height())/2, stageX = (stageW-(trans3DBoxes1.width()/2)), stageY = (stageH-(250/2)); //transformPerspective gives the element its own vanishing point //perspective allows all the child elements (orange boxes) to share the same vanishing point with each other //transformStyle:"preserve3d" allows the child elements to maintain their 3D position (noticeable only when their parent div is rotated in 3D space) TweenMax.set(trans3DBoxes1, {css:{transformPerspective:3000, transformStyle:"preserve-3d"}}); //saves a dozen lines of vendor-prefixed css ;) /* K, lets build a cube and place it boxes1[0] = frontside boxes1[1] = leftside boxes1[2] = rightside boxes1[3] = topside boxes1[4] = bottomside boxes1[5] = backside */ threeDTimeline.set(boxes1[0], {rotationX:0, rotationY:0, x:0, y:0, z:125, opacity:0.85}) .set(boxes1[1], {rotationX:0, rotationY:-90, x:-125, y:0, z:0, opacity:0.85}) .set(boxes1[2], {rotationX:0, rotationY:90, x:125, y:0, z:0, opacity:0.85}) .set(boxes1[3], {rotationX:90, rotationY:0, x:0, y:-125, z:0, opacity:0.85}) .set(boxes1[4], {rotationX:-90, rotationY:0, x:0, y:125, z:0, opacity:0.85}) .set(boxes1[5], {rotationX:0, rotationY:180, x:0, y:0, z:-125, opacity:0.85}) .set(trans3DBoxes1, {x:150, y:150, transformOrigin:"125px 125px 0px"}); // hover events boxes1.each(function (index, element) { $(element).hover(over, out); function over(){ TweenMax.to(element, 0.15, {opacity:0.33}); //threeDTimeline.pause(); } function out(){ TweenMax.to(element, 0.15, {opacity:0.85}); //threeDTimeline.play(); } }); threeDTimeline.to(trans3DBoxes1, 15, {css:{rotationY:360, rotationX:-720, transformOrigin:"125px 125px 0px"}, ease:Power0.easeNone}); function updateCube(){ stageW = ($(window).width())/2; stageH = ($(window).height())/2; stageX = (stageW-(trans3DBoxes1.width()/2)); stageY = (stageH-(250/2)); TweenMax.to(trans3DBoxes1, 1, {css:{x:stageX, y:stageY}}); }