Gamedev Canvas Workshop - lesson 3

Bounce off the walls.

by TR1N1TYF0XX

HTML

<canvas id="myCanvas" width="480" height="320"></canvas>

CSS

canvas { background: #000; }

JavaScript

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballcolor ="purple";

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2,true);
    ctx.fillStyle = ballcolor;
    /*ballcolor because the name of the variable that contains the balls color is ballcolor*/
    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;
        ballcolor= "red";
        /*this changes the balls color to red when it hits the left and right walls*/
    }
    if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
        ballcolor= "blue";
        /*this changes the balls color to red when it hits the top and bottom walls*/
    }
    
    x += dx;
    y += dy;
}

setInterval(draw, 5);