Bouncing ball

Animation

by arcm111

HTML

<div id="div">
	<canvas id="canvas"></canvas>
    <img draggable="false" id="image" src="http://www.clker.com/cliparts/b/a/b/0/1207156679935151925noxin_crosshairs.svg.hi.png" />
</div>
<center>
    <p>Score: <a>0</a></p>
</center>

CSS

body
{
	overflow: hidden;
}
#image
{
	position: absolute;
	width: 30px; height: 30px; pointer-events: none;
}
#div > canvas
{
	border: 2px solid DarkBlue;
	background-color: SteelBlue;
	cursor: none; display: block; margin: 0 auto;
}

JavaScript

var dx = 3;
var dy = 3;
var x = 100;
var y = 100;
var radius = 20;
var width = 400;
var height = 240;
var interval, div, image, canvas, ctx;

function startBall()
{
	image = document.getElementById ("image");
    canvas = document.getElementById ("canvas");
    ctx = canvas.getContext ("2d");
	div = document.getElementById ("div");
	canvas.onmousemove = function (e)
	{
		image.style.top = e.pageY + "px";
		image.style.left = e.pageX + "px";
	}
	canvas.width = width + 24;
	canvas.height = height + 24;
	ctx.scale (1, 1);
    launchBall();
}

function launchBall()
{
    if (x < 20 || x > width) dx = -dx;
    if (y < 20 || y > height) dy = -dy;
    x += dx;
    y += dy;
    ctx.clearRect (0, 0, width + 24, height + 24);
    ctx.beginPath();
    ctx.arc (x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = "Yellow";
    ctx.fill();
	requestAnimationFrame (launchBall);
}

window.addEventListener ('load', startBall, false);