JSFiddle - React, Tailwind, and code Playground

by alexdickson

CSS

canvas {
    background: #000; 
}

JavaScript

(function() {

    var canvas, ctx;

    var blocks = [];

    var player;

    var block = {
        width: 20,
        height: 10,
        padding: 8
    }

    var init = function() {

        canvas = document.createElement('canvas');

        canvas.width = 400;

        canvas.height = 300;


        ctx = canvas.getContext('2d');

        document.body.appendChild(canvas);

        generateBlocks();

        player = new Player(20);

        draw();


    }

    var generateBlocks = function() {

        for (var y = 0; y < 4; y++) {
            blocks[y] = [];
            for (var x = 0; x < 15; x++) {
                blocks[y][x] = 1;
            }
        }

    }

    var draw = function() {
        
        // Draw blocks
        var startX = canvas.width / 2 - blocks[0].length * block.width / 2;

        for (var y = 0; y < blocks.length; y++) {
            for (var x = 0; x < blocks[y].length; x++) {
                ctx.fillStyle = 'rgb(255, 100, ' + Math.floor(Math.random() * 255) + ')';

                var method = blocks[y][x] ? 'fill' : 'clear';

                ctx[method + 'Rect']((x * block.width) + startX, (y * block.height) + 20, block.width, block.height);

            }
        }
        
        // Draw player
        if ( ! player.x) {
            player.x = 100;
        }
        
        ctx.fillStyle = player.color;
        ctx.fillRect(player.x, canvas.height - player.height - 20, player.width, player.height);
    }

    var Player = function(width) {
        this.width = width;
        this.height = 20;
        this.x;
        this.color = 'blue';
        
        this.moveLeft = function() {
           this.x -= 20;
           draw();  
        }
        
    }

    document.onkeydown = function(event) {
        switch (event.keyCode) {

            // Up arrow
        case 38:
            player.moveLeft();
            break;
            // Down arrow
        case 40:
            player.moveRight();
            break;

       ...