Ball bounce easy
HTML
<canvas id="canvas" height="300" width="300" style="border:1px dotted #111;border-radius:100%;"
/>
CSS
(x − a)2 + (y − b)2 = r2
if (x -
JavaScript
var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
var WIDTH;
var HEIGHT;
var ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath();
//ctx.arc(150, 200, 10, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.fill();
function init() {
var ctx = document.getElementById("canvas").getContext("2d");
return setInterval(draw, 10);
}
function draw() {
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI, true);
ctx.closePath();
ctx.fill();
x += dx;
y += dy;
bounce();
}
function bounce() {
if( Math.pow(x - 150, 2) + Math.pow(y - 150, 2) > Math.pow(150, 2))
{
dx = -dx * (0.6 + (Math.random() * 0.8));
dy = -dy * (0.6 + (Math.random() * 0.8));
}
}
init();