Jason (jcreed) wrote,
Jason
jcreed

I really liked the effect of this small javascript canvas demo (which is basically just: have a bunch of particles, and set their current velocity to some Perlin noise at their current location) which was linked to by the wikipedia article on Perlin Noise.

Fiddled with it a bit to visualize the actual noise behind the particles, got this:
Perlin Noise


M = Math;
r = M.random;

s = [];
n = function(){
for (i = 8; i--;) {
s[i] = [~~(r()*3)-1, ~~(r()*3)-1]
}
}
n();

u = [];
for (i = 256; i--;) {
u[i] = ~~(r() * 256);
}

function z(k, t, l) {
F = .5 - t * t - l * l;
return (F < 0) ? 0 : M.pow(F, 4) * (s[k%8][0] * t + s[k%8][1] * l)
}

function q(k, t) {
e = (3-M.sqrt(3))/6;
a = (k + t) * .5*(M.sqrt(3)-1); // .36
m = ~~(k + a);
b = ~~(t + a);
a = (m + b) * e; // .2

c = k - (m - a);
j = t - (b - a);

C = c > j;

return 70 * (z(u[m + u[b]], c, j) +
z(u[m + C + u[b + !C]], c - C + e, j - !C + e) +
z(u[m + 1 + u[b + 1]], c - 1 + 2 * e, j - 1 + 2 * e))
};

c = document.body.children[0];
c.width = w = innerWidth;
c.height = h = innerHeight;
document.body.style.overflow = 'hidden';
d = c.getContext('2d');
N = Math.floor(w / 3);

x = [];
for(i = N; i--;) {
x[i] = {x:r()*w,y:r()*h};
}

setInterval(function() {
/*
if (r() < 1.0)
d.fillStyle = 'rgba(255,255,255,.01)';
else d.fillStyle = 'rgba(255,255,255,0)';
d.fillRect(0,0,w,h);
*/
d.fillStyle = 'rgba(255,255,255,0.1)';
for (i = N; i--;){
X = x[i];
a = q(X.x/300, X.y/300) * 120;

X.x += M.cos(a);
X.y += M.sin(a);

if (X.x < 0 || X.x > w || X.y < 0 || X.y > h) {
X.x = r()*w;
X.y = r()*h;
}
d.fillRect(X.x, X.y, 1, 1);
}
}, 33);

c.onclick=function(){

n();
for (var i = 0; i < w; i+= 10) {
for (var j = 0; j < h; j+= 10) {
d.fillStyle = 'rgba(' + Math.floor(255 * q(i/300, j/300)) + ',0,' + Math.floor(-255 * q(i/300, j/300)) + ',1)';
d.fillRect(i, j, 10, 10);
}
}


};
Tags: javascript
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 5 comments