-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (81 loc) · 2 KB
/
index.js
File metadata and controls
91 lines (81 loc) · 2 KB
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
84
85
86
87
88
89
90
91
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(vector) {
this.x += vector.x;
this.y += vector.y;
}
static random(minX, maxX, minY, maxY) {
return new Vector(
Vector.randomNumBetween(minX, maxX),
Vector.randomNumBetween(minY, maxY)
);
}
static randomNumBetween(min, max) {
return min + Math.random() * (max - min);
}
}
class Snowflake {
constructor(width, height) {
this.boundaryX = width;
this.boundaryY = height;
this.pos = Vector.random(0, width, 0, height);
this.vel = Vector.random(-0.3, 0.3, 0.3, 1);
this.acc = new Vector(0, 0);
this.radius = Vector.randomNumBetween(1, 4);
this.alpha = Vector.randomNumBetween(0.1, 0.9);
}
update() {
this.pos.add(this.vel);
this.vel.add(this.acc);
// check for wraparound
if (this.pos.x > this.boundaryX) {
this.pos.x = 0;
} else if (this.pos.y > this.boundaryY) {
this.pos.y = 0;
} else if (this.pos.x < 0) {
this.pos.x = this.boundaryX;
}
}
}
class Christmas {
constructor() {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
document.body.appendChild(this.canvas);
this.canvas.width = 800;
this.canvas.height = 800;
this.setup();
requestAnimationFrame(() => this.update());
}
setup() {
const NUMFLAKES = 500;
this.snowflakes = [];
for (let i = 0; i < NUMFLAKES; i++) {
this.snowflakes.push(new Snowflake(
this.canvas.width,
this.canvas.height,
));
}
}
update() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (let flake of this.snowflakes) {
flake.update();
this.ctx.fillStyle = `rgba(255, 255, 255, ${flake.alpha})`;
this.ctx.beginPath();
this.ctx.arc(
flake.pos.x,
flake.pos.y,
flake.radius,
0,
2 * Math.PI
);
this.ctx.fill();
}
requestAnimationFrame(() => this.update());
}
}
new Christmas();