I try to create a canvas with X * X of size, using hexagon shapes, currently I base on this reference, with some adaptations, my code until now look like this:
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const shapeType = 6;
const angle = 2 * Math.PI / shapeType;
const radius = 20;
function init() {
drawGrid(5);
}
init();
function drawGrid(size) {
for (let y = radius, i = 0; i < size; i++) {
y += radius * Math.sin(angle);
for (let x = radius, j = 0;
j < size;
x += radius * (1 + Math.cos(angle)), y += (-1) ** j++ * radius * Math.sin(angle)) {
drawHexagon(x, y);
}
}
}
function drawHexagon(x, y) {
context.beginPath();
for (let i = 0; i < shapeType; i++) {
let xx = x + radius * Math.cos(angle * i);
let yy = y + radius * Math.sin(angle * i);
context.lineTo(xx, yy);
}
context.closePath();
context.stroke();
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HexGrid</title>
<style>
.test {
display: flex;
justify-content: space-between;
}
.canvas {
border: 1px solid #000000;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500" class="canvas"></canvas>
<script src="main.js"></script>
</body>
</html>
Until now, every thing is good, but just with odd size, but if the size is even, I get this:
As a beginner in JavaScript, I'm blocked in this, any one have any idea how can I solve this please?
