JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500px" height="500px" style="background: #fff; magrin:20px;">Browser does not support canvas</canvas>
<img id="canvasImg" alt="Right click to save me!">
JavaScript
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.translate(0.5, 0.5);
// ----------------------------------------------------------
function Board(gridWidth, gridHeight, graphicSize) {
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
this.graphicSize = graphicSize;
this.planParts = [];
// no need to serialize this property
// but you have to rebuild it after loading from DB
this.grid = new Array(gridWidth * gridHeight)
}
Board.prototype = {
draw: function (ctx) {
this.drawGrid(ctx);
for (var i = 0; i < this.planParts.length; i++) {
this.planParts[i].draw(ctx);
}
},
canAdd: function (part) {
// uses getGrid to check no cell is already covered
// for (x) { for (y) { if this.getGrid(x,y) return false}}
// return true;
},
addPart: function (part) {
this.planParts.push(part);
// + setGrid for all covered cells
// for (x) { for (y) { this.setGrid(x,y,true)}}
},
getGrid: function (x, y) {
return this.grid[x + y * this.gridWidth];
},
setGrid: function (x, y, val) {
this.grid[x + y * this.gridWidth] = val;
},
drawGrid: function (ctx) {
ctx.strokeStyle = "black";
ctx.save();
ctx.scale(this.graphicSize, this.graphicSize);
ctx.lineWidth = 1 / this.graphicSize;
for (var x = 0; x <= this.gridWidth; x++) {
line(ctx, x, 0, x, this.gridHeight);
}
for (var y = 0; y <= this.gridHeight; y++) {
line(ctx, 0, y, this.gridWidth, y);
}
ctx.restore();
}
}
// ----------------------------------------------------------
function PlanPart(board, x, y, w, h) {
this.board = board;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
PlanPart.prototype = {
draw: function (ctx) {
...