简体   繁体   中英

Simplify table code in EaselJs

I've got a 2x3 table that I'm adding to EaselJS...currently I'm building it like this:

for (var i = 0; i < 6; i++) {
    if(i == 1 || i == 3 || i == 5) {
       var xPos = playersBoxW;
    } else { 
       var xPos = 0;
    }
    if(i == 2 || i == 3) { 
       var yPos = playersBoxH;
    } else if (i == 4|| i == 5) { 
       var yPos = playersBoxH*2;
    } else { 
       var yPos = 0;
    }
    playerBox[i] = new createjs.Container().set({x: xPos, y: yPos});
}

It just seems a very inefficient way of doing it and not useful if the table grows. Anyone else have an idea to simplify this?

Looking at your code I think this algorithm is essentially what it boils down to:

xPos seems to be equal to the integer division of i (by table width) times playersBoxW . eg if i = 3 and width is 2, then xPos is equal to playersBoxW times int division of 3/2 which is 1.

yPos seems to be equal to the integer division of i (by table height) times playersBoxH . eg if i = 4 and height = 3, then yPos is equal to playersBoxH times int division of 4/3 which is 1.

function integerDivision(a, b) {
    return Math.floor(a / b);
}

function makeTable(width, height, player, arr) {
     var xPos, yPos, size = width*height;
     for (var i = 0; i < size; i++) {
          xPos = player.boxW  * integerDivision(i, width);
          yPos = player.boxH  * integerDivision(i, height);
          arr[i] = new createjs.Container().set({x: xPos, y: yPos});
     }
     return arr;
}

Integer division is like regular division but you throw the remainder away. So in this case we round the number down: 3/2 = 1.5 => floor the result (round down) => 1


Side node: EaslJS containers can be expensive sometimes so be careful with them.

Containers have some overhead, so you generally shouldn't create a Container to hold a single child. [easljs doc]

If you are just trying to do row/column math, there is an easier way.

Here is your original example (with some code to make it work) http://jsfiddle.net/u3ds24y5/

You can just derive the column and row with a simple equation. This lets you change the number of columns and total count easily.

var column = i % num_columns;
var row = Math.floor(i / num_columns);
var x = column * column_width;
var y = row * row_height;

Here is an updated fiddle: http://jsfiddle.net/u3ds24y5/1/

Simplified code:

var cols = 2, total = 6; // Change these
for (var i = 0; i < total; i++) {
    var xPos = i % cols * playersBoxW,
        yPos = Math.floor(i/cols) * playersBoxH;
    // Create container, etc
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM