Skip to content

Instantly share code, notes, and snippets.

@CodeMyUI
Created February 26, 2018 01:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeMyUI/326aa3fe9aa54a132ec490f5826f1a0e to your computer and use it in GitHub Desktop.
Save CodeMyUI/326aa3fe9aa54a132ec490f5826f1a0e to your computer and use it in GitHub Desktop.
Confetti
<h1 class="title">Confetti</h1>
<canvas id="canvas"></canvas>
const canvasEl = document.querySelector('#canvas');
const w = canvasEl.width = window.innerWidth;
const h = canvasEl.height = window.innerHeight * 2;
function loop() {
requestAnimationFrame(loop);
ctx.clearRect(0,0,w,h);
confs.forEach((conf) => {
conf.update();
conf.draw();
})
}
function Confetti () {
//construct confetti
const colours = ['#fde132', '#009bde', '#ff6b00'];
this.x = Math.round(Math.random(10) * w);
this.y = Math.round(Math.random(10) * h)-(h/2);
this.rotation = Math.random(10)*360;
const size = Math.random(10)*(w/60);
this.size = size < 15 ? 15 : size;
this.color = colours[Math.round(Math.random(colours.length)*10-1)]
this.speed = this.size/7;
this.opacity = Math.random(10);
this.shiftDirection = Math.random(10) > 0.5 ? 1 : -1;
}
Confetti.prototype.border = function() {
if (this.y >= h) {
this.y = h;
}
}
Confetti.prototype.update = function() {
this.y += this.speed;
if (this.y <= h) {
this.x += this.shiftDirection/5;
this.rotation += this.shiftDirection*this.speed/100;
}
this.border();
};
Confetti.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, this.rotation, this.rotation+(Math.PI/2));
ctx.lineTo(this.x, this.y);
ctx.closePath();
ctx.globalAlpha = this.opacity;
ctx.fillStyle = this.color;
ctx.fill();
};
const ctx = canvasEl.getContext('2d');
const confNum = Math.floor(w / 5);
const confs = new Array(confNum).fill().map(_ => new Confetti());
loop();
body {
margin: 0;
width: 100vw;
height: 100vh;
position: relative;
}
canvas {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
}
.title {
position: absolute;
margin: 0;
width: 100vw;
height: 100vh;
font-family: 'Helvetica';
line-height: 100vh;
text-transform: uppercase;
font-weight: lighter;
color: #ccc;
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment