JSFiddle - React, Tailwind, and code Playground
by dp0ch
HTML
<canvas id="canvas"></canvas>
JavaScript
const cellSize = 50;
const fieldCellsW = 10;
const fieldCellsH = 20;
const canvas = document.getElementById('canvas');
canvas.width = cellSize * fieldCellsW;
canvas.height = cellSize * fieldCellsH;
const ctx = canvas.getContext('2d');
function drawField(field, posX, posY) {
// draw rects
ctx.fillStyle = 'grey';
for(let x = 0; x < fieldCellsW; x++) {
for(let y = 0; y < fieldCellsH; y++) {
ctx.fillStyle = field[x + y * fieldCellsW] || 'grey';
ctx.fillRect(posX + x * cellSize, posY + y * cellSize, cellSize, cellSize);
}
}
// draw lines
ctx.fillStyle = 'black';
for (let x = 1; x < fieldCellsW; x++) {
ctx.beginPath();
ctx.moveTo(posX + x * cellSize, posY);
ctx.lineTo(posX + x * cellSize, posY + cellSize * fieldCellsH);
ctx.stroke();
}
for (let y = 1; y < fieldCellsH; y++) {
ctx.beginPath();
ctx.moveTo(posX, posY + y * cellSize);
ctx.lineTo(posX + cellSize * fieldCellsW, posY + y * cellSize);
ctx.stroke();
}
}
function gameLoop() {
const field = ['green', 'green'];
const piece = [];
const drawPiece = (piece) => {
for(let x = 0; x < fieldCellsW; x++) {
for(let y = 0; y < fieldCellsH; y++) {
ctx.fillStyle= piece[x + y * fieldCellsW] || 'grey';
ctx.filLRect(posX + x * cellSIze, posY + y * cellSize, cellSize, cellSize);
}
}
}
const id = window.requestAnimationFrame((deltaTime) => {
drawField(field, 0, 0);
});
return () => window.cancelAnimationFrame(id);
}
gameLoop();