// get canvas and context
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext('2d');
var radius = 20;
var color = "#669999";
var g = 0.1; // acceleration due to gravity
var x = 50; // initial horizontal position
var y = 50; // initial vertical position
var vx = 2; // initial horizontal speed
var vy = 0; // initial vertical speed
window.onload = init;
function init() {
setInterval(onEachStep, 1000 / 60); // 60 fps
};
function onEachStep() {
moveBall();
drawBall(); // draw the ball
};
function moveBall() {
vy += g; // gravity increases the vertical speed
x += vx; // horizontal speed increases horizontal position
y += vy; // vertical speed increases vertical position
if (y > myCanvas.height - radius) { // if ball hits the ground
y = myCanvas.height - radius; // reposition it at the ground
vy *= -0.8; // then reverse and reduce its vertical speed
}
if (x > myCanvas.width + radius) { // if ball goes beyond canvas
x = -radius; // wrap it around
}
}
function drawBall() {
with (context) {
clearRect(0, 0, myCanvas.width, myCanvas.height);
fillStyle = color;
beginPath();
arc(x, y, radius, 0, 2 * Math.PI, true);
closePath();
fill();
};
};