wking-generativenoise.web.val.run
Readme

Generative Noise Demo

This is based on a post I wrote on Craft Lab

The article breaks down the basic building blocks that go into most generative projects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/** @jsxImportSource npm:react **/
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);
}
/**
* Simplex Noise generates a value between -1 and 1, but we are working with an
* array that will not accept a negative index. We will be converting the original
* noise range to fit the 0 to 1 scale we need.
*/
function getColorByNoise(colors: string[], noise: number) {
return colors[Math.floor(((noise + 1) / 2) * colors.length)];
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v20
May 30, 2024