This repository has been archived by the owner on Sep 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfetti.js
79 lines (57 loc) · 1.85 KB
/
confetti.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
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
let canvas = document.getElementById('confetti');
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var Height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
canvas.width = width;
canvas.height = Height;
let ctx = canvas.getContext('2d');
let pieces = [];
let numberOfPieces = 100;
let lastUpdateTime = Date.now();
function randomColor() {
let colors = ['#f00', '#0f0', '#00f', '#0ff', '#f0f', '#ff0'];
return colors[Math.floor(Math.random() * colors.length)];
}
function update() {
let now = Date.now(),
dt = now - lastUpdateTime;
for (let i = pieces.length - 1; i >= 0; i--) {
let p = pieces[i];
if (p.y > canvas.height) {
pieces.splice(i, 1);
continue;
}
p.y += p.gravity * dt;
p.rotation += p.rotationSpeed * dt;
}
while (pieces.length < numberOfPieces) {
pieces.push(new Piece(Math.random() * canvas.width, -20));
}
lastUpdateTime = now;
setTimeout(update, 1);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
pieces.forEach(function(p) {
ctx.save();
ctx.fillStyle = p.color;
ctx.translate(p.x + p.size / 2, p.y + p.size / 2);
ctx.rotate(p.rotation);
ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size);
ctx.restore();
});
requestAnimationFrame(draw);
}
function Piece(x, y) {
this.x = x;
this.y = y;
this.size = (Math.random() * 0.5 + 0.75) * 15;
this.gravity = (Math.random() * 0.5 + 0.75) * 0.1;
this.rotation = (Math.PI * 2) * Math.random();
this.rotationSpeed = (Math.PI * 2) * (Math.random() - 0.5) * 0.001;
this.color = randomColor();
}
while (pieces.length < numberOfPieces) {
pieces.push(new Piece(Math.random() * canvas.width, Math.random() * canvas.height));
}
update();
draw();