Creating a grid layout

Sometimes you want to create a bunch of objects laid out in a grid. There are a few ways to do this. Here’s the easiest way I found.

We’ll start with the basic template. I’ll add a size variable and a double for loop that goes from 0 to height on the y-axis and 0 to width on x.

function onGLC(glc) {
    glc.loop();
    // glc.playOnce();
    // glc.size(400, 400);
    // glc.setDuration(5);
    // glc.setFPS(20);
    // glc.setMode("single");
    // glc.setEasing(false);
    var list = glc.renderList,
        width = glc.w,
        height = glc.h;

        var size = 50;
        for(var y = 0; y < height; y += size) {
        for(var x = 0; x < width; x += size) {

        }
    }
}


The size variable represents the size of one cell in the grid. Here, I’m making square cells, but you could have a different variable for each axis and make non-square cells as well.

The loop starts x and y at 0 and increments them by size each time. Now we can add an object.

var size = 50;
for(var y = 0; y < height; y += size) {
    for(var x = 0; x < width; x += size) {
        list.addCircle({
            translationX: x,
            translationY: y,
        });
    }
}

Using translationX and translationY moves the origin of the canvas to the top left of each grid cell on each iteration. Now you can just draw your object assuming that it’s in a size x size rectangle. No fancy math needed to calculate the x and y positions. Here, I’ll center the circle within that rectangle. And animate it’s radius to a max of size / 2

var size = 50;
for(var y = 0; y < height; y += size) {
    for(var x = 0; x < width; x += size) {
        list.addCircle({
            translationX: x,
            translationY: y,
            x: size / 2,
            y: size / 2,
            radius: [size / 4, size / 2]
        });
    }
}

Here’s what this gives us.

grid

Pretty simple. No fancy math needed. Now we can make things a bit more interesting by messing with the phase property.

var size = 50;
for(var y = 0; y < height; y += size) {
    for(var x = 0; x < width; x += size) {
        list.addCircle({
            translationX: x,
            translationY: y,
            x: size / 2,
            y: size / 2,
            radius: [size / 4, size / 2],
            phase: x / width + y / height
        });
    }
}


gridphase

And then, simply by changing the size variable to a smaller value, like 20, and no other changes, we get this:

gridphase2

Leave a Reply