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.clearRect = function(x, y) {
        this.context.clearRect(x, y, this.tilesize, this.tilesize);
    };

    Renderer.prototype.drawCellRect = function(color, x, y, width) {
        this.clearRect(x, y);
        this.context.save();
        this.context.lineWidth = 1;
        this.context.strokeStyle = color;
        this.context.strokeRect((x + 0.5), (y + 0.5), (this.tilesize - 1), (this.tilesize - 1));
        this.context.restore();
    };

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

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

    Renderer.prototype.renderTileAt = function(map, tilesheet, i, j) {
      ...