JSFiddle - React, Tailwind, and code Playground

by helxsz

HTML

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Canvas Tile Grid</title>
    </head>
    <body>

        <div role="main">
            <canvas id="entities">Your browser does not support canvas</canvas>
        </div>

    </body>
</html>

CSS

html,
body {
    margin: 0;
    width: 100%;
    height: 100%;
}

canvas {
    display: block;
}

JavaScript

(function($){

    // Canvas rendering class
    var Renderer = function(canvas, width, height) {
        this.canvas   = canvas;
        this.context  = canvas.getContext('2d');
        this.tilesize = 32;
        this.onresize = function() {};

        this.resize(width, height);
    }

    Renderer.prototype.resize = function(width, height) {
        this.canvas.width = width;
        this.canvas.height = height;
        this.onresize();
    }

    Renderer.prototype.getWidth = function() {
        return this.canvas.width;
    }

    Renderer.prototype.getHeight = function() {
        return this.canvas.height;
    }

    Renderer.prototype.drawCellRect = function(color, x, y) {
        this.context.save();
        this.context.lineWidth = 2;
        this.context.strokeStyle = color;
        this.context.translate(x, y);
        this.context.strokeRect(0, 0, this.tilesize, this.tilesize);
        this.context.restore();
    }

    Renderer.prototype.drawTile = function(image, x, y, sx, sy) {
        this.context.save();
        this.context.drawImage(image, sx, sy, this.tilesize, this.tilesize, x, y, this.tilesize, this.tilesize);
        this.context.restore();
    }

    Renderer.prototype.clearRect = function(x, y) {
        this.context.clearRect(x, y, this.tilesize, this.tilesize);
    }

    Renderer.prototype.renderMap = function(map, tilesheet) {
        for(var i = 0; i < (this.getHeight() / this.tilesize); i++) {
            for(var j = 0; j < (this.getWidth() / this.tilesize); j++) {

                var row = i * this.tilesize;
                var col = j * this.tilesize;

                if(map && (i in map) && (j in map[i])) {
                    this.drawTile(tilesheet, col, row, map[i][j][0], map[i][j][1]);
                } else {
                    this.drawCellRect('#333', col, row);
                }
            }
        }
    }

    // Use the correct document according to the window argument
    var document = $.document;
    var...