Simple bouncing ball
CSS
body {
margin: 0px;
overflow: hidden;
}
JavaScript
var canvas = document.getElementById("c");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var particle = new Particle(canvas.width / 2, canvas.height / 2);
particle.size = 5;
particle.velX = 2;
particle.velY = -4;
// initial way
// setInterval(animate, 1000 / 30);
// "correct" way
(function animate() {
// clear
//ctx.clearRect(0, 0, canvas.width, canvas.height);
// apply fade
ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// bounce
if (particle.y >= canvas.height && particle.velY > 0) {
particle.velY *= -0.9;
particle.y = canvas.height;
}
// walls
if ((particle.x < 0 && particle.velX < 0) || (particle.x >= canvas.width && particle.velX > 0)) {
particle.velX *= -0.8;
}
// update and render
particle.update();
particle.render(ctx);
setTimeout(animate, 1000 / 30);
})()
function Particle(x, y) {
this.x = x;
this.y = y;
this.velX = 0;
this.velY = 0;
this.gravity = .5;
this.size = 1;
this.color = "red";
this.update = function() {
this.velY += this.gravity;
this.x += this.velX;
this.y += this.velY;
};
this.render = function(c) {
c.fillStyle = this.color;
c.beginPath();
c.arc(this.x, this.y, this.size, 0, Math.PI * 2, true);
c.fill();
}
}