JSFiddle - React, Tailwind, and code Playground
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>Hexagonal Grid with Dynamic Aspect Ratio</title>
<style>
</style>
<script>
class Game {
constructor(gameConfig, gridConfig) {
this.rows = gameConfig.rows;
this.cols = gameConfig.cols;
this.iconSizeRatio = gameConfig.iconSizeRatio; // Added iconSizeRatio to gameConfig
this.hexGridSize = gridConfig.hexGridSize;
this.hexGridPadding = gridConfig.hexGridPadding;
this.hexGridColor = gridConfig.hexGridColor;
this.hexGridBorderColor = gridConfig.hexGridBorderColor;
this.hexGridBgColor = gridConfig.hexGridBgColor;
this.occupiedPositions = new Set();
this.cosPiOver6 = Math.cos(Math.PI / 6);
this.hexWidth = 2 * this.hexGridSize * this.cosPiOver6;
this.hexHeight = this.hexGridSize * 1.5;
this.updateGridDimensions();
}
updateGridDimensions() {
this.gridWidth = (this.cols - 1) * this.hexWidth + this.hexWidth + this.hexGridSize + this.hexGridPadding * 2;
this.gridHeight = (this.rows - 1) * this.hexHeight + this.hexHeight + this.hexGridPadding * 2;
}
// Modified to optionally accept width and height; defaults to calculated dimensions if not provided
setupCanvas(id, width = this.gridWidth, height = this.gridHeight) {
let canvas = document.getElementById(id);
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = id;
document.getElementById('canvasContainer').appendChild(canvas);
}
canvas.width = width; canvas.height = height;
gameData.canvasData = {canvasID: canvas.id, canvasHeight:height, canvasWidth:width}
//gameData.gridData = {gridCols:this.cols, gridRows:this.rows}
return...
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: white;
}
.canvas-container {
position: relative;
width: 50%;
height: 50%;
border-radius: 20px;
background: yellow;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
background: transparent;
}