Simple Ball Animation
by brouser
HTML
<canvas id="myCanvas" style="background-color:white;" height="300" width="300">Canvas element not loading.</canvas>
CSS
body {
background: grey;
/* border: 3px dotted blue; */
}
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx;
var x = 150;
var y = 150;
var dx = 1;
var dy = 1;
function init() {
ctx = canvas.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
x += dx;
y += dy;
if (x > 300 || x < 0) {
dx *= -1;
}
if (y > 300 || y < 0) {
dy *= -1;
}
}
init();