← Volver
Dibujar tablero en Javascript
Publicado el 1 de mayo de 2025
Javascript
Una función bastante útil a la hora de dibujar un tablero en Javascript para utilizarlo en un juego puede ser de la siguiente manera.
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const FPS = 60;
const BOARD_COLS = 10;
const BOARD_ROWS = 10;
const board = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
const drawBoard = () => {
const tileWidth = canvas.width / BOARD_COLS;
const tileHeight = canvas.height / BOARD_ROWS;
for (let i = 0; i < BOARD_ROWS; i++) {
for (let j = 0; j < BOARD_COLS; j++) {
if (board[i][j] === 1) {
ctx.fillStyle = "red";
ctx.fillRect(j * tileWidth, i * tileHeight, tileWidth, tileHeight);
}
}
}
};
const clearCanvas = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
setInterval(() => {
clearCanvas();
drawBoard();
}, 1000 / FPS);
window.addEventListener("resize", () => {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
});
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;