GLSL shader example
Random Numbers
GLSL has no random() function. Here is the one-line hash everyone uses, and how to turn it into random grid cells.
Live example
Edit the code and the preview updates as you type.
How it works
A shader runs the same code on every pixel at the same time, so there is no shared random number generator to call. Instead, shaders use a hash: a function that scrambles its input so much that the output looks random, while the same input always gives the same output.
random(st) does this in three steps:
dot(st, vec2(12.9898, 78.233))squashes the 2D input into one number.sin(...) * 43758.5453turns it into a wave and multiplies it into a very large number, so tiny input changes produce huge output changes.fract(...)keeps only the decimal digits, which are the chaotic part, giving a value from 0% to 100%.
Feeding it floor(uv * 16.0) instead of raw uv gives every pixel in a cell the same input, so you get random blocks instead of TV static.
Try changing it
| Change | Result |
|---|---|
random(cell + ...) to random(uv) | Per-pixel static |
16.0 to 4.0 | Big random blocks |
floor(u_time * 2.0) to 0.0 | The pattern freezes |
vec3(r) to vec3(step(0.5, r)) | Pure black and white cells, about half each |
Note: this hash uses highp precision. On some mobile GPUs with mediump, the large multiplication loses precision and visible patterns appear.
Built-in functions used
Learn it step by step
- Hash Grid NoiseGenerate a random value per grid cell using a small hash function.
- Noise FunctionsLearn and implement common noise functions in GLSL, such as random noise, value noise, and gradient noise (like a simplified version of Perlin noise), used for generating various procedural textures and effects.
- 2D Value NoiseBuild smooth noise by interpolating hashed grid corners.