JSFiddle - React, Tailwind, and code Playground
by mvasilkov
HTML
<canvas width="256" height="256"></canvas>
JavaScript
var map = Array(256), i, j, x, y
for (x = 0; x < 256; ++x) {
map[x] = Array(256)
}
for (i = 0; i < 25000; ++i) {
rollParticle()
}
function rollParticle() {
var _x = 64 + (0|Math.random() * 128)
var _y = 64 + (0|Math.random() * 128)
var ttl = 50, near, val
inc(_x, _y)
while (ttl--) {
near = []
near.push([norm(_x - 1), norm(_y - 1)])
near.push([norm(_x), norm(_y - 1)])
near.push([norm(_x + 1), norm(_y - 1)])
near.push([norm(_x - 1), norm(_y)])
near.push([norm(_x + 1), norm(_y)])
near.push([norm(_x - 1), norm(_y + 1)])
near.push([norm(_x), norm(_y + 1)])
near.push([norm(_x + 1), norm(_y + 1)])
near.sort(function (a, b) { return map[a[0]][a[1]] - map[b[0]][b[1]] })
val = map[near[0][0]][near[0][1]]
while (map[near[near.length - 1][0]][near[near.length - 1][1]] > val) {
near.pop()
}
_x = near[0|Math.random() * near.length][0]
_y = near[0|Math.random() * near.length][1]
inc(_x, _y)
}
}
function inc(_x, _y) {
if (!map[_x][_y]) map[_x][_y] = 1
else ++map[_x][_y]
}
function norm(a) {
if (a < 0) return a + 256
if (a > 255) return a - 256
return a
}
var canvas = document.getElementsByTagName('canvas')[0],
c = canvas.getContext('2d'),
iData = c.getImageData(0, 0, 256, 256),
data = iData.data
for (i = 0; i < 256 * 256 * 4; i += 256 * 4) {
for (j = 0; j < 256 * 4; j += 4) {
x = j / 4
y = i / (256 * 4)
data[i + j] = map[x][y] * 4
data[i + j + 1] = map[x][y] * 4
data[i + j + 2] = map[x][y] * 4
data[i + j + 3] = 255
}
}
c.putImageData(iData, 0, 0)