import Alea from "npm:alea";
import { renderToString } from "npm:react-dom@18/server";
import { createNoise2D } from "npm:simplex-noise";
export default (req: Request) => {
const generator = Alea(Math.random() * 100);
const noise2D = createNoise2D(generator);
const rows = createArrayOfLength(Math.floor(Math.random() * 100));
const columns = createArrayOfLength(Math.floor(Math.random() * 40));
const xSmoothness = 20;
const ySmoothness = 20;
const boxSize = 3;
const simpleColorsFill = [
"#7662f9",
"#3176f6",
"#2eefb5",
"#97dc41",
"#efbf2e",
"#ff75dd",
"#f28d45",
];
return new Response(
renderToString(
<html>
<main>
<div
style={{
position: "relative",
display: "flex",
minHeight: "205px",
alignItems: "center",
justifyContent: "center",
background: "#fdf2f8",
padding: "24px",
}}
>
<svg
width={rows.length * boxSize}
height={columns.length * boxSize}
viewBox={`0 0 ${rows.length} ${columns.length}`}
>
{rows.map(x =>
columns.map(y => {
const noise = noise2D(x / xSmoothness, y / ySmoothness);
const color = getColorByNoise(simpleColorsFill, noise);
return (
<rect
x={x}
y={y}
fill={color}
width="1"
height="1"
key={`demo-preview-pixel-${x}-${y}`}
/>
);
})
)}
</svg>
</div>
</main>
</html>,
),
{ headers: { "Content-Type": "text/html" } },
);
};
function createArrayOfLength(length: number): number[] {
return Array.from(Array(length === 0 ? 1 : length), (_, i) => i);
}
function getColorByNoise(colors: string[], noise: number) {
return colors[Math.floor(((noise + 1) / 2) * colors.length)];
}