Bouncing
MouseOver on canvas above
Code
<canvas id="canvas" width="200" height="200" style="background-color: #f9f9f9;cursor:pointer;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var y=50,
speed=5,
gravity=0.08,
animation;
function draw() {
ctx.fillStyle = 'rgba(255, 255, 255, .5)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.fillStyle="red"
ctx.arc(100, y, 15, 0, Math.PI * 2, true);
ctx.fill();
speed+=gravity;
y+=speed;
if (y > canvas.height-15) {
y = canvas.height-15; //To limit the ball till the ground
speed = -speed*0.6; //To bounce back when touch the ground
}
animation = requestAnimationFrame(draw);
}
canvas.addEventListener('mouseover', function() {
animation = requestAnimationFrame(draw);
});
canvas.addEventListener('mouseout', function() {
cancelAnimationFrame(animation);
});
</script>