Skip to content

Instantly share code, notes, and snippets.

@maujim
Created February 7, 2025 02:37
Show Gist options
  • Save maujim/fbb7acea1a99dbef76a33e024871f348 to your computer and use it in GitHub Desktop.
Save maujim/fbb7acea1a99dbef76a33e024871f348 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
const TiledBackground = ({ name = 'MUKUND', debugMode = false }) => {
const [rows, setRows] = useState(0);
const [columns, setColumns] = useState(0);
const [hoveredIndex, setHoveredIndex] = useState(null);
useEffect(() => {
const updateDimensions = () => {
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const tileSize = 40; // Size of each tile in pixels
const gap = 4; // Gap between tiles
const padding = 16; // Padding around the grid
const totalWidth = viewportWidth - 2 * padding;
const totalHeight = viewportHeight - 2 * padding;
const calculatedColumns = Math.floor(totalWidth / (tileSize + gap));
const calculatedRows = Math.floor(totalHeight / (tileSize + gap));
setColumns(calculatedColumns);
setRows(calculatedRows);
};
updateDimensions();
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}, []);
const handleMouseEnter = index => {
setHoveredIndex(index);
};
const handleMouseLeave = () => {
setHoveredIndex(null);
};
const gridStyle = {
display: 'grid',
gridTemplateColumns: `repeat(${columns}, 40px)`,
gap: '4px',
padding: '16px',
width: `calc(100vw - 32px)`,
height: `calc(100vh - 32px)`,
boxSizing: 'border-box',
margin: '0 auto',
backgroundColor: debugMode ? '#f5f5f5' : 'black',
};
const tileStyle = {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '40px',
height: '40px',
border: debugMode ? '1px solid #ccc' : 'none',
color: debugMode ? '#000' : '#fff',
fontSize: '24px',
fontWeight: 'bold',
transition: 'opacity 2s',
};
const nameLength = name.length;
const totalTiles = rows * columns;
return (
<div style={gridStyle}>
{Array.from({ length: totalTiles }).map((_, index) => {
const row = Math.floor(index / columns);
const col = index % columns;
const letterIndex = (col + row) % nameLength;
const letter = name[letterIndex] || '';
return (
<div
key={index}
style={{
...tileStyle,
opacity: hoveredIndex === index ? 1 : 0,
transition: hoveredIndex === index ? 'opacity 0s' : 'opacity 2s',
}}
onMouseEnter={() => handleMouseEnter(index)}
onMouseLeave={handleMouseLeave}
>
{letter}
</div>
);
})}
</div>
);
};
export { TiledBackground as App };
@maujim
Copy link
Author

maujim commented Feb 7, 2025

test it out here: https://playcode.io/react

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment