Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active February 1, 2025 00:16
Show Gist options
  • Save Garciat/494719f903661f2348fe3bce1923c874 to your computer and use it in GitHub Desktop.
Save Garciat/494719f903661f2348fe3bce1923c874 to your computer and use it in GitHub Desktop.
Flooring // A random pattern that I once saw at an airport. Click to randomize.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Flooring</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
height: 100%;
margin: 0;
}
canvas {
touch-action: none;
}
</style>
<script>
function main() {
let screenW = document.body.clientWidth;
let screenH = document.body.clientHeight;
let canvas = document.createElement('canvas');
canvas.width = screenW;
canvas.height = screenH;
document.body.appendChild(canvas);
let ctx = canvas.getContext('2d');
let rectRatio = 4;
let rectW = 40;
let rectH = rectW * rectRatio;
let colors = ['hsl(0, 0%, 15%)', 'hsl(0, 0%, 30%)', 'hsl(0, 0%, 50%)'];
let lastChoice = null;
// Avoid choosing the same color twice in a row
function chooseColor() {
while (true) {
let color = arrayChoice(colors);
if (color !== lastChoice) {
lastChoice = color;
return color;
}
}
}
function render() {
draw(ctx, rectW, rectH, chooseColor);
}
render();
canvas.addEventListener("click", () => render());
}
function draw(ctx, rectW, rectH, colorF) {
ctx.save();
ctx.translate(0, -rectH);
for (let i = 0; i < 40; ++i) {
for (let j = 0; j < 40; ++j) {
ctx.save();
ctx.translate(Math.floor(i/2) * hyp(rectH, rectH), j * hyp(rectW, rectW));
ctx.rotate(Math.PI / 4 * Math.pow(-1, i + 1));
ctx.fillStyle = colorF();
ctx.fillRect(0, 0, rectW, rectH);
ctx.restore();
}
}
ctx.restore();
}
function hyp(a, b) {
return Math.sqrt(a * a + b * b);
}
function randomInt(a, b) {
return a + Math.floor((b - a) * Math.random());
}
function arrayChoice(arr) {
return arr[randomInt(0, arr.length)];
}
window.addEventListener('load', main);
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment