CSS3 制作魔方 - 形成魔方


道路千萬條,安全第一條!

魔方結構解析

從魔方的外觀來看,可以有多種方式來表達它的組成,從而也有多種方式來形成一個魔方。如:

  • 由六個面組成
  • 由若干層組成
  • 由多個方塊組成

無論哪種方式,都可以制作魔方。只是,不同的方式對后續的其它操作會有影響,有些方式甚至會導致利用已有的特性無法直接表達。因此,在這項選擇上小糾結一下,理出最易於理解和實施(往往也容易自以為是)的方案是有益的。

這里我們選擇“由多個方塊組成”的方式來形成魔方。

於是得到魔方的基本結構為:一個魔方由多個魔方格(cube)組成,一個魔方格由多個版面(block)組成。

一些基本要素的表示

六個方向表示:上(up)、下(down)、左(left)、右(right)、前(front)、后(back)

六種顏色表示:黃色(yellow)、白色(white)、橙色(orange)、紅色(red)、藍色(blue)、綠色(green)

初始的魔方組成形式為:上黃,下白,左橙,右紅,前藍,后綠。

繪制魔方格

一個魔方格也有六個方向,每個方向一個版面。在魔方中,一個魔方格可見的只有 1 至 3 個版面。

為了處理方便,每一個魔方格我們總是從前面來看它,從而上、下、左、右、前、后對於每一個魔方格而言都是確定的位置。

版面的繪制

首先,定義版面(block)的基礎樣式:

.block { 
    position: absolute; 
    margin: 0 auto;  
    border:solid 2px black;
    border-radius:3px;
    /* 寬高包含邊框 */
    box-sizing:border-box; 
    /* 旋轉原點 */
    transform-origin:0 0 0;
}

一個版面,默認總是“前面”,我們通過旋轉將其旋轉到指定的方向,每個方向確定的規則如下:

上:為繞 x 軸逆向 90 度,即 rotateX(-90deg)

下:y 軸的 top屬性增加一格后繞 x 軸逆向 90 度

左:繞 y 軸 90 度,即 rotateY(90deg)

右:x 軸的 left 屬性增加一格后繞 y 軸 90 度

前:本尊不用動

后:z 軸向后平移一格即可,即 translateZ(size px)

為此,我們通過 javascript 定義一個 Block 類,接收方向、顏色與一格大小作為參數,實現動態繪制版面。

<script>
/** 版面 block 類 
 * direct 方向
 * color  顏色
 * size   邊長大小
**/
function Block(direct, color, size){
    this.direct = direct;
    this.color = color;
    this.size = size;
    // 繪制過的 UI 元素對象
    this.Element = null;

    // 在父容器中繪制
    this.DrawIn = function(cubeElement){
        var e = this.Element || document.createElement('div');
        e.style.width = this.size + "px";
        e.style.height = this.size + "px";

        var top = (this.direct == 'down' ? this.size : 0);
        var left = (this.direct == 'right' ? this.size : 0);

        e.style.top = top + "px";
        e.style.left = left + "px";
        e.style.backgroundColor = this.color;

        var rx = (this.direct == 'up' || this.direct == 'down' ? -90 : 0);
        var ry = (this.direct == 'left' || this.direct == 'right' ? 90 : 0);;
        var tz = (this.direct == 'back' ? this.size : 0);

        e.style["transform"] = "rotateX(" + rx + "deg) rotateY(" + ry + "deg) translateZ(-" + tz + "px)";
        e.className = "block"; 
        this.Element = e;
        cubeElement.appendChild(e);
    };
}

function onload(){
    var blockLeft = new Block('left', 'red', 50);
    var blockTop = new Block('up', 'yellow', 50);
    var blockRight = new Block('right', 'green', 50);

    blockLeft.DrawIn( document.querySelector(".wrap") );
    blockTop.DrawIn( document.querySelector(".wrap") );
    blockRight.DrawIn( document.querySelector(".wrap") );
}
</script>

效果如下:

魔方格的繪制

有了版面的繪制,魔方格可以看到是版面的一個集合,我們根據需要組合版面即可。

首先,我們定義一個魔方格的基礎樣式 cube:

.cube { 
    position: absolute;
    /* 子元素版面是需要三維空間的 */
    transform-style: preserve-3d;   
}

為了動態繪制魔方格,我們定義一個魔方格的 Cube 類,指定大小,以及指明所需要各版面的方向及顏色即可。為了能將魔方格排列成魔方,可以為魔方格設置一個其位於魔方這個三維體的坐標位置,默認坐標總是(0,0,0)。而魔方的三維坐標我們定義如下:

自左向右為 x 坐標,以三階為例可取值:0,1,2

自上向下為 y 從標,以三階為例可取值:0,1,2

自前向后為 z 坐標,以三階為例可取值:0,1,2

/** 魔方格 Cube 類
 * blockSize 為魔方格的邊長代表大小
 * directColorArray 為指定方向與顏色的數組
 *                  形式為 [direct,color,direct,color,...]  
 * x,y,z 為在魔方中的坐標,未指定時默認為0,0,0
**/
function Cube(blockSize, directColorArray, x, y, z){
    this.x = x | 0; 
    this.y = y | 0; 
    this.z = z | 0;
    this.blockSize = blockSize;
    this.blocks = []; 
    /* 根據參數建立 Block 對象 */
    for(var i=0; i < directColorArray.length / 2; i++){
        this.blocks.push(new Block(directColorArray[ i*2 ], directColorArray[ i*2 + 1 ], this.blockSize)); 
    }

    // 繪制過的 UI 元素對象
    this.Element = null;

    // 在父容器中繪制
    this.DrawIn = function(boxElement, x, y, z){ 
        this.x = this.x | x;
        this.y = this.y | y;
        this.z = this.z | z;
        var e = this.Element || document.createElement('div');
        e.style.width = this.blockSize + "px";
        e.style.height = this.blockSize + "px";  
        e.style["transform"] = "translate3d(" + (x * this.blockSize) + "px," + (y * this.blockSize) + "px,-" + (z * this.blockSize) + "px) "; 
        e.className = "cube";  

        for(var i=0; i < this.blocks.length; i++) {  
            this.blocks[i].DrawIn(e);
        }

        this.Element = e;

        boxElement.appendChild(e);
    };
}

以下代碼,繪制兩個魔方格:

function onload(){
    var cube1 = new Cube(50, ['left', 'red', 'up', 'yellow', 'back', 'green']);
    var cube2 = new Cube(50, ['right', 'red', 'up', 'yellow', 'back', 'green']);

    cube1.DrawIn( document.querySelector(".wrap") ); 
    cube2.DrawIn( document.querySelector(".wrap"), 2, 0, 0 ); 
}

效果如下:

形成魔方

同樣,為了包裹起整個魔方,我們定義一個魔方的基礎樣式,magicBox:

.magicBox {
    position: absolute;
    transform-style: preserve-3d;  
}

接下來,再定義一個 MagicBox 的類,根據魔方初始的擺放格局“上黃,下白,左橙,右紅,前藍,后綠”,我們可以根據指定的維度自動生成其所需要的魔方格,所有的魔方格,均通過平移的方式放置到所屬的坐標。

/** 魔方 MagicBox 類
 * dimension 階數
 * blockSize 每小格大小
 **/
function MagicBox(dimension, blockSize){
    this.dimension = dimension;
    this.blockSize = blockSize;
    this.cubes = [];

    this.MakeDefaultCubes = function(){
        this.cubes = [];
        for(var x=0; x < this.dimension; x++){
            for(var y=0; y < this.dimension; y++){
                for(var z=0; z < this.dimension; z++){
                    var cube = this.MakeDefaultCube(x, y, z);
                    if(cube){
                      this.cubes.push(cube);
                    }
                }
            }
        }
    };

    /* 根據魔方格在階數中的位置生成魔方格,魔方內部的格子忽略 */
    this.MakeDefaultCube = function(x, y, z){
        var max = this.dimension - 1;
        var dc = [];
        if(x == 0) dc.push("left", "orange"); else if(x == max) dc.push("right", "red");
        if(y == 0) dc.push("up", "yellow"); else if(y == max) dc.push("down", "white");			
        if(z == 0) dc.push("front", "blue"); else if(z == max) dc.push("back", "green");
        if(dc.length == 0) return null;
        var cube = new Cube(this.blockSize, dc, x, y, z); 
        return cube;
    }

    // 構造時自動產生初始魔方格
    this.MakeDefaultCubes();
    // 繪制過的 UI 元素對象
    this.Element = null;
    // 在父容器中繪制
    this.DrawIn = function(domElement){ 
        var e = this.Element || document.createElement('div');
        e.style.width = (this.dimension * this.blockSize) + "px";
        e.style.height = (this.dimension * this.blockSize) + "px";  
        e.className = "magicBox";  

        for(var i=0; i < this.cubes.length; i++) { 
            this.cubes[i].DrawIn(e);
        }
        this.Element = e;
        domElement.appendChild(e);
    }; 
} 

通過以下代碼繪制一個三階魔方:

var magicBox = new MagicBox(3, 50);
magicBox.DrawIn( document.querySelector(".wrap") );

效果如下:

附本文完整 HTML 頁面

以下為本文完整的代碼文檔,復制到記事本中,保存為.html即可在谷歌瀏覽器中運行。

<!DOCTYPE html>
<html> 
<head>
    <meta charset="utf-8" /> 
    <title>CSS3 魔方</title>
    <!-- 樣式部分全寫這里 -->
    <style>  
    .wrap {
        transform-style: preserve-3d;
        width: 300px;  height: 300px; 
        position: relative;  /* 定位起點元素 */
        border-top:solid 1px gray;  /* x 軸 */
        border-left:solid 1px gray;  /* y 軸 */
        /* 傾斜一點方能見立體效果 */
        transform: rotateX(-30deg) rotateY(-30deg); 
    }

    /* z 軸正方向 */
    .zaxis_p { 
        position:absolute; 
        width : 300px;
        height:1px;  
        border-top:solid 1px gray; 
        /* xy面上,90度立起來就是 z */
        transform: rotateY(-90deg); 
        /* 立起來的旋轉點 */
        transform-origin:0 0 0; 
    }

    /* z 軸負方向 */
    .zaxis_n { 
        position:absolute; 
        width : 300px;
        height:1px;  
        border-top:dashed 1px gray; /*(虛線)*/
        transform: rotateY(90deg);
        transform-origin:0 0 0; 
    }

    .block { 
        position: absolute; 
        margin: 0 auto;  
        border:solid 2px black;
        border-radius:3px;
        /* 寬高包含邊框 */
        box-sizing:border-box; 
        transform-origin:0 0 0;
    }

    .cube { 
        position: absolute;
        /* 子元素版面是需要三維空間的 */
        transform-style: preserve-3d;   
    }

    .magicBox {
        position: absolute;
        transform-style: preserve-3d;  
    }

    </style> 

<script>
/** 版面 block 類 
 * direct 方向
 * color  顏色
 * size   邊長大小
**/
function Block(direct, color, size){
    this.direct = direct;
    this.color = color;
    this.size = size;
    // 繪制過的 UI 元素對象
    this.Element = null;

    // 在父容器中繪制
    this.DrawIn = function(cubeElement){
        var e = this.Element || document.createElement('div');
        e.style.width = this.size + "px";
        e.style.height = this.size + "px";

        var top = (this.direct == 'down' ? this.size : 0);
        var left = (this.direct == 'right' ? this.size : 0);

        e.style.top = top + "px";
        e.style.left = left + "px";
        e.style.backgroundColor = this.color;

        var rx = (this.direct == 'up' || this.direct == 'down' ? -90 : 0);
        var ry = (this.direct == 'left' || this.direct == 'right' ? 90 : 0);;
        var tz = (this.direct == 'back' ? this.size : 0);

        e.style["transform"] = "rotateX(" + rx + "deg) rotateY(" + ry + "deg) translateZ(-" + tz + "px)";
        e.className = "block"; 
        this.Element = e;
        cubeElement.appendChild(e);
    };
}

/** 魔方格 Cube 類
 * blockSize 為魔方格的邊長代表大小
 * directColorArray 為指定方向與顏色的數組
 *                  形式為 [direct,color,direct,color,...]  
 * x,y,z 為在魔方中的坐標,未指定時默認為0,0,0
**/
function Cube(blockSize, directColorArray, x, y, z){
    this.x = x | 0; 
    this.y = y | 0; 
    this.z = z | 0;
    this.blockSize = blockSize;
    this.blocks = []; 
    /* 根據參數建立 Block 對象 */
    for(var i=0; i < directColorArray.length / 2; i++){
        this.blocks.push(new Block(directColorArray[ i*2 ], directColorArray[ i*2 + 1 ], this.blockSize)); 
    }

    // 繪制過的 UI 元素對象
    this.Element = null;

    // 在父容器中繪制
    this.DrawIn = function(boxElement, x, y, z){ 
        this.x = x | this.x;
        this.y = y | this.y;
        this.z = z | this.z;
        var e = this.Element || document.createElement('div');
        e.style.width = this.blockSize + "px";
        e.style.height = this.blockSize + "px";  
        e.style["transform"] = "translate3d(" + (this.x * this.blockSize) + "px," + (this.y * this.blockSize) + "px,-" + (this.z * this.blockSize) + "px) "; 
        e.className = "cube";  

        for(var i=0; i < this.blocks.length; i++) {  
            this.blocks[i].DrawIn(e);
        }

        this.Element = e;

        boxElement.appendChild(e);
    };
}

/** 魔方 MagicBox 類
 * dimension 階數
 * blockSize 每小格大小
 **/
function MagicBox(dimension, blockSize){
    this.dimension = dimension;
    this.blockSize = blockSize;
    this.cubes = [];

    this.MakeDefaultCubes = function(){
        this.cubes = [];
        for(var x=0; x < this.dimension; x++){
            for(var y=0; y < this.dimension; y++){
                for(var z=0; z < this.dimension; z++){
                    var cube = this.MakeDefaultCube(x, y, z);
                    if(cube){
                      this.cubes.push(cube);
                    }
                }
            }
        }
    };

    /* 根據魔方格在階數中的位置生成魔方格,魔方內部的格子忽略 */
    this.MakeDefaultCube = function(x, y, z){
        var max = this.dimension - 1;
        var dc = [];
        if(x == 0) dc.push("left", "orange"); else if(x == max) dc.push("right", "red");
        if(y == 0) dc.push("up", "yellow"); else if(y == max) dc.push("down", "white");			
        if(z == 0) dc.push("front", "blue"); else if(z == max) dc.push("back", "green");
        if(dc.length == 0) return null;
        var cube = new Cube(this.blockSize, dc, x, y, z); 
        return cube;
    }

    // 構造時自動產生初始魔方格
    this.MakeDefaultCubes();
    // 繪制過的 UI 元素對象
    this.Element = null;
    // 在父容器中繪制
    this.DrawIn = function(domElement){ 
        var e = this.Element || document.createElement('div');
        e.style.width = (this.dimension * this.blockSize) + "px";
        e.style.height = (this.dimension * this.blockSize) + "px";  
        e.className = "magicBox";  

        for(var i=0; i < this.cubes.length; i++) { 
            this.cubes[i].DrawIn(e);
        }
        this.Element = e;
        domElement.appendChild(e);
    }; 
} 

function onload(){
    /* 版面繪制示例
    var blockLeft = new Block('left', 'red', 50);
    var blockTop = new Block('up', 'yellow', 50);
    var blockRight = new Block('right', 'green', 50);

    blockLeft.DrawIn( document.querySelector(".wrap") );
    blockTop.DrawIn( document.querySelector(".wrap") );
    blockRight.DrawIn( document.querySelector(".wrap") );
    */

    /* 魔方格繪制示例
    var cube1 = new Cube(50, ['left', 'red', 'up', 'yellow', 'back', 'green']);
    var cube2 = new Cube(50, ['right', 'red', 'up', 'yellow', 'back', 'green']);

    cube1.DrawIn( document.querySelector(".wrap") ); 
    cube2.DrawIn( document.querySelector(".wrap"), 2, 0, 0 ); 
    */

    //* 魔方繪制示例
    var magicBox = new MagicBox(3, 50);
    magicBox.DrawIn( document.querySelector(".wrap") );
    //*/
}
</script>
</head>

<body style="padding:300px;" onload="onload()">
  <div class="wrap">
    <div class="zaxis_p"></div> 
    <div class="zaxis_n"></div>  
  </div>
</body>

</html>

關注微信公眾號“時間維度”,讓我們走過一段時空交織的時光。


免責聲明!

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



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