JSFiddle - React, Tailwind, and code Playground

by v4nz666

HTML

<canvas id="gameCanvas" width="320" height="640"></canvas>http://jsfiddle.net/v4nz666/14yLvo08/1/#tidy

JavaScript

// Size of the board
var rows = 20;
var cols = 10;

// Size of the blocks in image
var size = 32;

// Position of our green block
var y = 0;
var x = 0; // This won't change, we'll just increment y...
var flip = 1; // The direction we're moving in
// Only need to grab these once, then they can be accessed over and over
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
canvas.height = size * rows;
canvas.width = size * cols;

function drawBoard() {
    var colors = ['#FFFFFF', '#000000'];
    var square = 0;
    for (var row = 0; row < rows; row++) {
        for (var col = 0; col < cols; col++) {
            var x = col * size;
            var y = row * size;

            ctx.fillStyle = colors[square++ % colors.length];
            ctx.fillRect(x, y, size, size);
        }
        square += colors.length - 1;
    }
}

function drawGreenBlock() {
    ctx.fillStyle = '#00BB00';
    ctx.fillRect(x, y * size, size, size);
}

function main() {
    drawBoard();
    drawGreenBlock();
    y = y + flip;

    if (y >= rows) {
        y = rows;
        flip = -1 * flip;
    } else if (y < 0) {
        y = 0;
        flip = -1 * flip;
    }
}

setInterval(main, 30); // main() will be called every 30 ms