22222

by velo_ninja

HTML

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Perfectly Centered Hexagonal Grid with Units</title>
    <style>        
    </style>
        
    <script>
    	class HexGrid {
    		constructor(canvas, rows, cols, hexSize, spacing) {
          this.canvas = canvas;
          this.ctx = canvas.getContext('2d');
          this.rows = rows;
          this.cols = cols;
          this.hexSize = hexSize;
          this.spacing = spacing;
          this.hexWidth = 2 * hexSize * Math.cos(Math.PI / 6) + spacing;
          this.hexHeight = hexSize * 1.5 + spacing;
          this.gridWidth = (cols - 1) * this.hexWidth + this.hexWidth + (hexSize - spacing);
          this.gridHeight = (rows - 1) * this.hexHeight + this.hexHeight + spacing;
          this.canvas.width = this.gridWidth;
          this.canvas.height = this.gridHeight;
          this.gridTop = this.hexHeight / 2;
          this.gridLeft = this.hexWidth / 2;
          this.units = [];
          this.occupiedPositions = new Set();
          this.drawGrid();
      	}

        // Method to check if a cell is occupied by a unit or obstacle
        checkOccupied(row, col) {const posKey = `${row},${col}`;
            return this.occupiedPositions.has(posKey);
        }
        drawHexagon(x, y, color) {
          const ctx = this.ctx;
          ctx.beginPath();
          for (let i = 0; i < 6; i++) {
            const angle = Math.PI / 3 * i + Math.PI / 6;
            const px = x + this.hexSize * Math.cos(angle) + this.gridLeft;
            const py = y + this.hexSize * Math.sin(angle) + this.gridTop;
            if (i === 0) ctx.moveTo(px, py);
            else ctx.lineTo(px, py);
          }
          ctx.closePath();
          ctx.fillStyle = color;
          ctx.fill();
          ctx.strokeStyle = gridBorderColor;
          ctx.stroke();
        }
        drawGrid() {
          for (let row = 0; row <...