Refactor square drawing
Make square drawing modular and a member function of Canvas. Issue #3
This commit is contained in:
@@ -5,39 +5,47 @@ const INDEX_LETTERS = "abcdefgh";
|
|||||||
export class Canvas {
|
export class Canvas {
|
||||||
constructor() {
|
constructor() {
|
||||||
this._canvas = document.createElement("canvas");
|
this._canvas = document.createElement("canvas");
|
||||||
|
this._ctx = this._canvas.getContext("2d");
|
||||||
let boardSide = BOX_SIDE * 8 + INDEX_MARGIN;
|
let boardSide = BOX_SIDE * 8 + INDEX_MARGIN;
|
||||||
this._canvas.width = boardSide;
|
this._canvas.width = boardSide;
|
||||||
this._canvas.height = boardSide;
|
this._canvas.height = boardSide;
|
||||||
document.body.appendChild(this._canvas);
|
document.body.appendChild(this._canvas);
|
||||||
this.drawChessBoard();
|
this.drawChessBoard();
|
||||||
}
|
}
|
||||||
|
decideColor(r, c) {
|
||||||
|
if ((r + c) % 2) return "#c0c0c0";
|
||||||
|
else return "#ffffff";
|
||||||
|
}
|
||||||
|
drawSquareColor(color, r, c) {
|
||||||
|
const crtStyle = this._ctx.fillStyle;
|
||||||
|
this._ctx.fillStyle = color;
|
||||||
|
this._ctx.fillRect(
|
||||||
|
c * BOX_SIDE + INDEX_MARGIN,
|
||||||
|
r * BOX_SIDE + INDEX_MARGIN,
|
||||||
|
BOX_SIDE,
|
||||||
|
BOX_SIDE
|
||||||
|
);
|
||||||
|
this._ctx.fillStyle = crtStyle;
|
||||||
|
}
|
||||||
drawChessBoard() {
|
drawChessBoard() {
|
||||||
// Draw squares
|
// Draw squares
|
||||||
let ctx = this._canvas.getContext("2d");
|
|
||||||
ctx.fillStyle = "#c0c0c0";
|
|
||||||
for (let r = 0; r < 8; r++) {
|
for (let r = 0; r < 8; r++) {
|
||||||
for (let c = 0; c < 8; c++) {
|
for (let c = 0; c < 8; c++) {
|
||||||
if ((r + c) % 2)
|
this.drawSquareColor(this.decideColor(r, c), r, c);
|
||||||
ctx.fillRect(
|
|
||||||
c * BOX_SIDE + INDEX_MARGIN,
|
|
||||||
r * BOX_SIDE + INDEX_MARGIN,
|
|
||||||
BOX_SIDE,
|
|
||||||
BOX_SIDE
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Draw letters
|
// Draw letters
|
||||||
ctx.fillStyle = "black";
|
this._ctx.fillStyle = "black";
|
||||||
let fontsize = INDEX_MARGIN / 2;
|
let fontsize = INDEX_MARGIN / 2;
|
||||||
ctx.font = `${fontsize}px Monospace`;
|
this._ctx.font = `${fontsize}px Monospace`;
|
||||||
for (let idx = 0; idx < 8; idx++) {
|
for (let idx = 0; idx < 8; idx++) {
|
||||||
ctx.fillText(
|
this._ctx.fillText(
|
||||||
INDEX_LETTERS[idx],
|
INDEX_LETTERS[idx],
|
||||||
BOX_SIDE * idx + BOX_SIDE / 2 + INDEX_MARGIN - fontsize / 4,
|
BOX_SIDE * idx + BOX_SIDE / 2 + INDEX_MARGIN - fontsize / 4,
|
||||||
INDEX_MARGIN / 2
|
INDEX_MARGIN / 2
|
||||||
);
|
);
|
||||||
ctx.fillText(
|
this._ctx.fillText(
|
||||||
(8 - idx).toString(),
|
(8 - idx).toString(),
|
||||||
INDEX_MARGIN / 2 - fontsize / 4,
|
INDEX_MARGIN / 2 - fontsize / 4,
|
||||||
BOX_SIDE * idx + BOX_SIDE / 2 + INDEX_MARGIN + fontsize / 4
|
BOX_SIDE * idx + BOX_SIDE / 2 + INDEX_MARGIN + fontsize / 4
|
||||||
|
|||||||
Reference in New Issue
Block a user