Arrow Grid Follow
by smombartz
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrow Grid</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="grid-container"></div>
<script>
</script>
</body>
</html>
CSS
/* Grid container styles */
#grid-container {
display: grid;
width: 100%;
height: 100vh;
}
/* Grid item styles */
.grid-item {
display: flex;
justify-content: center;
align-items: center;
}
/* Arrow SVG styles */
.arrow {
transition: transform 0s ease; /* Smooth rotation */
}
JavaScript
// Variables to configure grid and arrow animation
const svgSize = 10; // Size of the SVG (in pixels)
const gridGap = 20; // Gap between grid items (in pixels)
const maxOffset = 40; // Maximum offset (in degrees) for arrows furthest from the mouse
const smoothingFactor = 1; // Factor to smooth out the interpolation
const rotationSpeed = 0.25; // Rotation speed (in seconds)
// SVG markup
const svgMarkup = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" fill="none" width="${svgSize}" height="${svgSize}" class="arrow">
<path d="M1 20L20 1L40 20" stroke="currentColor"/>
<line x1="20" y1="1" x2="20" y2="40" stroke="currentColor"/>
</svg>
`;
// Reference to the parent container
const container = document.getElementById('grid-container');
// Set up grid styles dynamically
container.style.gridTemplateColumns = `repeat(auto-fit, minmax(${svgSize}px, 1fr))`;
container.style.gap = `${gridGap}px`;
// Populate the grid with enough SVGs to fill the screen
const totalArrows = 500; // Arbitrary large number to ensure it fills the space
for (let i = 0; i < totalArrows; i++) {
const gridItem = document.createElement('div');
gridItem.classList.add('grid-item');
gridItem.innerHTML = svgMarkup;
container.appendChild(gridItem);
}
// Track the continuous angle and smooth interpolation
let continuousAngle = 0;
// Add mousemove event listener to calculate rotation angle
document.addEventListener('mousemove', (e) => {
const { clientX, clientY } = e; // Get mouse position
const centerX = window.innerWidth / 2; // Center of the screen (X-axis)
const centerY = window.innerHeight / 2; // Center of the screen (Y-axis)
// Calculate the base angle relative to the center of the screen
const dx = clientX - centerX; // Horizontal distance from center
const dy = clientY - centerY; // Vertical distance from center
const baseAngle = Math.atan2(dy, dx) * (180 / Math.PI) + 90; // Adjust for SVG's initial orientation
// Calculate the shortest path...