-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_walk.js
47 lines (36 loc) · 1.03 KB
/
random_walk.js
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
class RandomWalk
{
step = 10;
constructor(canvasId)
{
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext("2d", { willReadFrequently: true});
this.w = this.canvas.width;
this.h = this.canvas.height;
this.ctx.fillStyle = "#000011";
this.ctx.fillRect(0, 0, this.w, this.h);
this.x = this.w/2;
this.y = this.h/2;
this.walk();
}
// Brownian walk
walk()
{
var r = Math.random()*4;
if (this.x >= this.w) this.x -= this.w;
if (this.x < 0) this.x += this.w;
if (this.y < 0) this.y += this.h;
if (this.y >= this.h) this.y -= this.h;
this.ctx.strokeStyle = 'white';
this.ctx.globalAlpha = 0.2;
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
if (r < 1) this.x += this.step;
else if (r < 2) this.y -= this.step;
else if (r < 3) this.x -= this.step;
else this.y += this.step;
this.ctx.lineTo(this.x, this.y);
this.ctx.stroke();
requestAnimationFrame(this.walk.bind(this));
}
}