Make board dimensions global
This commit is contained in:
@@ -1,34 +1,37 @@
|
||||
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 INDEX_LETTERS = 'abcdefgh';
|
||||
|
||||
function drawChessBoard(canvas) {
|
||||
let ctx = canvas.getContext('2d');
|
||||
|
||||
let indexMargin = (canvas.width + canvas.height) / 2 / 16;
|
||||
let w = canvas.width - indexMargin;
|
||||
let h = canvas.height - indexMargin;
|
||||
let bw = w / 8;
|
||||
let bh = h / 8;
|
||||
|
||||
// Draw squares
|
||||
ctx.fillStyle = '#c0c0c0';
|
||||
for (let r = 0; r < 8; r++) {
|
||||
for (let c = 0; c < 8; c++) {
|
||||
if ((r + c) % 2) ctx.fillRect(bw*c+indexMargin, bh*r+indexMargin, bw, bh);
|
||||
if ((r + c) % 2) ctx.fillRect(c*BOX_WIDTH + INDEX_MARGIN,
|
||||
r*BOX_HEIGHT + INDEX_MARGIN,
|
||||
BOX_WIDTH, BOX_HEIGHT);
|
||||
}
|
||||
}
|
||||
|
||||
// Draw letters
|
||||
let indexLetters = 'abcdefgh';
|
||||
ctx.fillStyle = 'black';
|
||||
let fontsize = indexMargin / 2;
|
||||
ctx.font = fontsize.toString() + 'px Monospace';
|
||||
let fontsize = INDEX_MARGIN / 2;
|
||||
ctx.font = `${fontsize}px Monospace`;
|
||||
for (let idx = 0; idx < 8; idx++) {
|
||||
ctx.fillText(indexLetters[idx],
|
||||
bw*idx + bw/2 + indexMargin - fontsize / 4,
|
||||
indexMargin / 2);
|
||||
ctx.fillText(INDEX_LETTERS[idx],
|
||||
BOX_WIDTH*idx + BOX_WIDTH/2 + INDEX_MARGIN - fontsize / 4,
|
||||
INDEX_MARGIN / 2);
|
||||
ctx.fillText((8-idx).toString(),
|
||||
indexMargin / 2 - fontsize / 4,
|
||||
bh*idx + bh/2 + indexMargin + fontsize / 4);
|
||||
INDEX_MARGIN / 2 - fontsize / 4,
|
||||
BOX_HEIGHT*idx + BOX_HEIGHT/2 + INDEX_MARGIN + fontsize / 4);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user