Gamedev Canvas Workshop - lesson 3
Bounce off the walls.
by Zecheng Hu
HTML
<canvas id="myCanvas" width="480" height="320"></canvas>
CSS
canvas { background: #eee; }
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 8;
var x = canvas.width/3;
var y = canvas.height-30;
var dx = 3;
var dy = -3;
var randomColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
randomColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
ctx.fillStyle = randomColor;
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius ) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius ) {
dy = -dy;
}
x += dx;
y += dy;
}
setInterval(draw, 5);