Confetti

html5 confetti

by Javier Sosa

HTML

<div id="content">
  Hello World
  <br /> I love confetti!
  <br />
  <div class="buttonContainer">
    <button id="stopButton">Stop Confetti</button>
    <button id="startButton">Drop Confetti</button>
  </div>
</div>
<canvas id="canvas"></canvas>

CSS

* {
  margin: 0;
  padding: 0;
}

body {
  /*You can use any kind of background here.*/
  background: transparent;
}

canvas {
  display: block;
  position: relative;
  zindex: 1;
  pointer-events: none;
}

#content {
  text-align: center;
  width: 500px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -250px;
  margin-top: -150px;
  color: silver;
  font-family: verdana;
  font-size: 45px;
  font-weight: bold;
}

.buttonContainer {
  display: inline-block;
}

button {
  padding: 5px 10px;
  font-size: 20px;
}

JavaScript

(function () {
    // globals
    var canvas;
    var ctx;
    var W;
    var H;
    var mp = 150; //max particles
    var particles = [];
    var angle = 0;
    var tiltAngle = 0;
    var confettiActive = true;
    var animationComplete = true;
    var deactivationTimerHandler;
    var reactivationTimerHandler;
    var animationHandler;

    // objects

    var particleColors = {
        colorOptions: ["DodgerBlue", "OliveDrab", "Gold", "pink", "SlateBlue", "lightblue", "Violet", "PaleGreen", "SteelBlue", "SandyBrown", "Chocolate", "Crimson"],
        dualColorOptions: [
        {'main': "DodgerBlue", 'alt': 'steelblue'}, 
        {'main': "OliveDrab", 'alt': 'DarkOliveGreen'}, 
        {'main': "Gold", 'alt': 'DarkKhaki'}, 
        {'main': "Pink", 'alt': 'PaleVioletRed'}, 
        {'main': "lightblue", 'alt': 'LightSteelBlue'}, 
        {'main': "Violet", 'alt': 'Orchid'}, 
        {'main': "PaleGreen", 'alt': 'YellowGreen'}, 
        {'main': "SandyBrown", 'alt': 'Peru'}, 
        {'main': "Chocolate", 'alt': 'Sienna'}, 
        {'main': "Crimson", 'alt': 'FireBrick'}],
        colorIndex: 0,
        colorIncrementer: 0,
        colorThreshold: 10,
        getColor: function () {
            if (this.colorIncrementer >= 10) {
                this.colorIncrementer = 0;
                this.colorIndex++;
                if (this.colorIndex >= this.dualColorOptions.length) {
                    this.colorIndex = 0;
                }
            }
            this.colorIncrementer++;
            return this.dualColorOptions[this.colorIndex];
        }
    }

    function confettiParticle(colorOptions) {
        this.x = Math.random() * W; // x-coordinate
        this.y = (Math.random() * H) - H; //y-coordinate
        this.r = RandomFromTo(10, 30); //radius;
        this.d = (Math.random() * mp) + 10; //density;
        this.colorOptions = colorOptions;
        this.tilt = Math.floor(Math.random() * 10) - 10;
        this.tiltAngleIncremental = (Math.random() *...