commit 0a565527c871499a4f58fdb83175eb1a8cfa9978f1b71044f9a5119f111166fb Author: Moses Rolston Date: Wed Apr 2 11:00:33 2025 -0700 add hex animation diff --git a/README.org b/README.org new file mode 100644 index 0000000..7be0a23 --- /dev/null +++ b/README.org @@ -0,0 +1,5 @@ +* JavaScript Animations + +** HexGrid +Animation which fades in and out a small hex patterned across the screen. +demo: hexgrid.html diff --git a/js/hex_animation.js b/js/hex_animation.js new file mode 100755 index 0000000..39f5ce6 --- /dev/null +++ b/js/hex_animation.js @@ -0,0 +1,79 @@ +// script.js +var canvas = document.getElementById('hexmap'); +var ctx = canvas.getContext('2d'); + +function resizeCanvas() { + var headerHeight = document.querySelector('header').clientHeight; + var headerWidth = document.querySelector('header').clientWidth; + canvas.width = headerWidth; + canvas.height = headerHeight; +} + +window.addEventListener('resize', resizeCanvas); +resizeCanvas(); + +const hexagonAngle = Math.PI / 6; // 30 degrees in radians +const sideLength = 15; +const hexHeight = Math.sin(hexagonAngle) * sideLength; +const hexRadius = Math.cos(hexagonAngle) * sideLength; +const hexRectangleHeight = sideLength + 2 * hexHeight; +const hexRectangleWidth = 2 * hexRadius; + +ctx.strokeStyle = "#CCCCCC"; +ctx.lineWidth = 1; + +let opacityValues = []; + +function initializeOpacityValues() { + for (let i = 0; i < Math.ceil(canvas.height / (hexHeight * 1.5)); i++) { + let row = []; + for (let j = 0; j < Math.ceil((canvas.width - (i % 2) * hexRadius) / hexRectangleWidth); j++) { + row.push(Math.random()); + } + opacityValues.push(row); + } +} + +function drawHexagon(x, y, opacity) { + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + let angle = Math.PI / 3 * i; + ctx.lineTo( + x + hexRadius * Math.cos(angle), + y + hexRadius * Math.sin(angle) + ); + } + ctx.closePath(); + ctx.globalAlpha = opacity; + ctx.stroke(); + ctx.globalAlpha = 1; // Reset global alpha after drawing +} + +function drawBoard() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + for (let i = 0; i < opacityValues.length; i++) { + let offset = (i % 2) * hexRadius; + for (let j = 0; j < opacityValues[i].length; j++) { + drawHexagon( + j * hexRectangleWidth + offset, + i * (hexHeight * 1.5), + opacityValues[i][j] + ); + } + } +} + +function animate() { + for (let i = 0; i < opacityValues.length; i++) { + for (let j = 0; j < opacityValues[i].length; j++) { + opacityValues[i][j] += Math.random() * 0.1 - 0.05; + if (opacityValues[i][j] > 1) opacityValues[i][j] = 1; + if (opacityValues[i][j] < 0) opacityValues[i][j] = 0; + } + } + drawBoard(); + requestAnimationFrame(animate); +} + +initializeOpacityValues(); +animate();