1. 程式人生 > >3D骰子

3D骰子

CSS3 製作3D骰子

html:

<body>
<div id="box">
    <div class="box2">
        <div>上</div>
        <div>下</div>
        <div>左</div>
        <div>右</div>
        <div>前</div>
        <div>後</div>
    </div>
</div>
</body>

style:

<style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        /*html,body{
            overflow: hidden;
            height: 100%;
        }*/
        #box{
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            width: 300px;
            height: 300px;
            border: 1px solid;

            /*景深(數值越大,越不明顯)*/
            perspective: 2000px;
        }
        #box > .box2{
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            width: 200px;
            height: 200px;

            /*動畫時長*/
            transition: 3s;

            /*開啟3D*/
            transform-style: preserve-3d;
            /*定位基點:(x,y,length)*/
            transform-origin: center center -100px;
        }
        #box > .box2 div{
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: rgba(111,111,111,.8);
            font: 80px/200px "微軟雅黑";
            text-align: center;

            /*影藏背面*/
            backface-visibility: hidden;
        }
        #box > .box2 > div:nth-child(1){
            top: -200px;
            transform-origin: bottom;
            transform: rotateX(90deg);
        }
        #box > .box2 > div:nth-child(2){
            top: 200px;
            transform-origin: top;
            transform: rotateX(-90deg);
        }
        #box > .box2 > div:nth-child(3){
            left: -200px;
            transform-origin: right;
            transform: rotateY(-90deg);
        }
        #box > .box2 > div:nth-child(4){
            left: 200px;
            transform-origin: left;
            transform: rotateY(90deg);
        }
        #box > .box2 > div:nth-child(5){
            /*‘前’面不用處理*/
            /*z-index: 1;*/
        }
        #box > .box2 > div:nth-child(6){
            /*‘後’面向Z軸向裡面去200px*/
            transform: translateZ(-200px) rotateX(180deg);
        }
        #box:hover .box2{
            /*旋轉父元素box2
             *三個引數(X,Y,Z)軸,再加上一個旋轉的度數
             * */
            transform: rotate3d(3,2,1,360deg);
        }
    </style>