HTML5 Canvas Chess board
Build a simple Canvas Chess board
Let’s build a simple chess board with Canvas primitives
Html
The basic HTML with script.js and style.css.
Our canvas has 800x800 dimension.
<html lang="en">
<head>
<title>Canvas Chess board</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>
<body>
<canvas id="chess" width="800" height="800">
Chess board
</canvas>
<script src="script.js"></script>
</body>
</html>
Styles
#chess {
border: 1px solid;
display: block;
margin: 0 auto;
width: 800px;
height: 800px;
}
Js
Now, the most interesting part. Drawing process
Colors
We define two colors we ll use everywhere.
let lightCellColor = '#ddb180';
let darkCellColor = '#7c330c';
Initial board with two cells
window.onload = function () {
let canvas = document.getElementById('chess');
let context = canvas.getContext("2d");
let lightCellColor = '#ddb180';
let darkCellColor = '#7c330c';
context.strokeStyle = "black";
context.strokeRect(200, 200, 400, 400);
context.fillStyle = lightCellColor;
context.fillRect(200, 200, 50, 50);
context.fillStyle = darkCellColor;
context.fillRect(250, 200, 50, 50);
}
Now we’ll add all the cells in the loop instead of duplicate the code.
We define a few initial variables
let x = 200;
let y = 200;
let chessBoardWidth = 400;
let chessBoardHeight = 400;
let delta = chessBoardWidth / 8;
And our look to create all the cells
for (let i = 1; i <= 8; i++) {
for (let j = 1; j <= 8; j++) {
context.fillStyle = (i + j) % 2 == 0 ? lightCellColor : darkCellColor;
context.fillRect(
x + delta * (i - 1),
y + delta * (j - 1),
delta,
delta
);
}
}
This line permit us change the color each time
context.fillStyle = (i + j) % 2 == 0 ? lightCellColor : darkCellColor;
You can rewrite it with if-else in this way
if ((i + j) % 2 == 0 ) {
context.fillStyle = lightCellColor;
} else {
context.fillStyle = darkCellColor
}
And here we draw each cell with i, j, delta variables.
context.fillRect(
x + delta * (i - 1),
y + delta * (j - 1),
delta,
delta
);
Thank you for your attention.
Thank you for your attention.
Do you need help with web or mobile development? Feel free to contact me here.
P.S. I really appreciate your like or share 🙏.