Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
encody committed Oct 24, 2016
0 parents commit 61ded5d
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Confetti Animation

A simple confetti animation in JavaScript, drawn on the HTML5 canvas.

[Video Guide](https://youtu.be/GiA6ls9mOL4)
76 changes: 76 additions & 0 deletions confetti.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
let canvas = document.getElementById('confetti');

canvas.width = 640;
canvas.height = 480;

let ctx = canvas.getContext('2d');
let pieces = [];
let numberOfPieces = 50;
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();
12 changes: 12 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Confetti</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<canvas id="confetti"></canvas>
<script src="confetti.js"></script>
</body>
</html>

0 comments on commit 61ded5d

Please sign in to comment.