Refactor project away from html

Main reason is to dynamically specify the dimensions for the
board canvas.
This commit is contained in:
2021-05-31 20:58:48 +02:00
parent 1f6bb25ed7
commit 0e6cd7e2c0
2 changed files with 20 additions and 17 deletions

View File

@@ -1,13 +1,16 @@
var _canvas = document.getElementById('chessBoard');
const INDEX_MARGIN = (_canvas.width + _canvas.height) / 2 / 16;
const BOARD_WIDTH = _canvas.width - INDEX_MARGIN;
const BOARD_HEIGHT = _canvas.height - INDEX_MARGIN;
const BOX_WIDTH = BOARD_WIDTH / 8;
const BOX_HEIGHT = BOARD_HEIGHT / 8;
const BOX_SIDE = 80;
const INDEX_MARGIN = BOX_SIDE / 2;
const INDEX_LETTERS = 'abcdefgh';
function createCanvas() {
let canvas = document.createElement('canvas');
let boardSide = BOX_SIDE * 8 + INDEX_MARGIN;
canvas.width = boardSide;
canvas.height = boardSide;
document.body.appendChild(canvas);
return canvas
}
function drawChessBoard(canvas) {
let ctx = canvas.getContext('2d');
@@ -15,9 +18,9 @@ function drawChessBoard(canvas) {
ctx.fillStyle = '#c0c0c0';
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
if ((r + c) % 2) ctx.fillRect(c*BOX_WIDTH + INDEX_MARGIN,
r*BOX_HEIGHT + INDEX_MARGIN,
BOX_WIDTH, BOX_HEIGHT);
if ((r + c) % 2) ctx.fillRect(c*BOX_SIDE + INDEX_MARGIN,
r*BOX_SIDE + INDEX_MARGIN,
BOX_SIDE, BOX_SIDE);
}
}
@@ -27,11 +30,11 @@ function drawChessBoard(canvas) {
ctx.font = `${fontsize}px Monospace`;
for (let idx = 0; idx < 8; idx++) {
ctx.fillText(INDEX_LETTERS[idx],
BOX_WIDTH*idx + BOX_WIDTH/2 + INDEX_MARGIN - fontsize / 4,
BOX_SIDE*idx + BOX_SIDE/2 + INDEX_MARGIN - fontsize / 4,
INDEX_MARGIN / 2);
ctx.fillText((8-idx).toString(),
INDEX_MARGIN / 2 - fontsize / 4,
BOX_HEIGHT*idx + BOX_HEIGHT/2 + INDEX_MARGIN + fontsize / 4);
BOX_SIDE*idx + BOX_SIDE/2 + INDEX_MARGIN + fontsize / 4);
}
}
@@ -39,11 +42,11 @@ function drawPiece(canvas, piece, field) {
let canvasRect = canvas.getBoundingClientRect();
let rc = boardIndexToRowCol(field);
let im = new Image(BOX_WIDTH, BOX_HEIGHT);
let im = new Image(BOX_SIDE, BOX_SIDE);
im.src = `./icons/${piece}.svg`;
im.onload = () => {
let topPx = canvasRect.top + INDEX_MARGIN + rc[0]*BOX_HEIGHT + window.pageYOffset;
let leftPx = canvasRect.left + INDEX_MARGIN + rc[1]*BOX_WIDTH + window.pageXOffset;
let topPx = canvasRect.top + INDEX_MARGIN + rc[0]*BOX_SIDE + window.pageYOffset;
let leftPx = canvasRect.left + INDEX_MARGIN + rc[1]*BOX_SIDE + window.pageXOffset;
im.style.position = 'absolute';
im.style.top = `${topPx}px`;
im.style.left = `${leftPx}px`;
@@ -84,5 +87,6 @@ function boardIndexToRowCol(boardIndex) {
return [row, col];
}
var _canvas = createCanvas();
drawChessBoard(_canvas);
_setupBoard(_canvas);