-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
94 lines (76 loc) · 2 KB
/
index.ts
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
92
93
94
class Flake {
x: number;
y: number;
vx: number;
vy: number;
radius: number;
alpha: number;
img: HTMLImageElement;
constructor() {
this.x = 0;
this.y = 0;
this.vx = 0;
this.vy = 0;
this.radius = 0;
this.alpha = 0;
// set image here so that it is only loaded once
this.img = new Image();
this.img.src = "assets/img.png";
this.img.width = 100;
this.img.height = 100;
this.reset();
}
reset() {
this.x = this.random(0, window.innerWidth);
this.y = this.random(-window.innerHeight, -50);
this.vx = this.random(-3, 3);
this.vy = this.random(2, 5);
this.radius = this.random(1, 4);
this.alpha = this.random(0.1, 0.9);
}
random(min: number, max: number) {
return min + Math.random() * (max - min + 1);
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.y + this.radius > window.innerHeight) {
this.reset();
}
}
}
class Snow {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
flakes: Flake[];
flakeCount: number;
constructor() {
this.canvas = document.getElementById("snowflake") as HTMLCanvasElement;
this.ctx = this.canvas.getContext("2d")!;
this.flakes = [];
this.flakeCount = window.innerWidth / 20;
for (let i = 0; i < this.flakeCount; i++) {
this.flakes.push(new Flake());
}
this.canvas.width = window.innerWidth - 20;
this.canvas.height = window.innerHeight - 20;
window.addEventListener("resize", () => {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
});
document.body.appendChild(this.canvas);
this.render();
}
render() {
this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.flakes.forEach((flake) => {
flake.update();
this.ctx.save();
this.ctx.globalAlpha = flake.alpha;
this.ctx.drawImage(flake.img, flake.x, flake.y);
this.ctx.restore();
});
requestAnimationFrame(this.render.bind(this));
}
}
new Snow();