sample: simple canvas animation

by sii_side

HTML

<canvas id="rakka" width="600" height="380"></canvas>

JavaScript

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

var canvas = document.querySelector('#rakka');
var ctx = canvas.getContext('2d');

var Particle = function(scale, color, vx, vy) {
  this.scale = scale;
  this.color = color;
  this.vx = vx;
  this.vy = vy;
  this.position = {
    x: 0,
    y: 0
  };
};

Particle.prototype.draw = function() {
  ctx.beginPath();
  ctx.arc(this.position.x, this.position.y, this.scale, 0, 2 * Math.PI, false);
  ctx.fillStyle = this.color;
  ctx.fill();
};

Particle.prototype.update = function() {
  this.position.y -= this.vy;
  this.draw();
};

var particle = new Particle(12, '#D0A000', 5, -6);
particle.position.x = (canvas.width / 2) - 6;
particle.position.y = 100;

loop();

function loop() {
  requestAnimFrame(loop);
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  particle.update();
}