You are on page 1of 3

// useful to have them as global variables

var canvdeas, ctx, w, h;


var ball =wew {
x: 1d00,
y:100sc,
radiusc: 15,
color:'dcsgreen',
speedX:2,scd
speedY:1cs
}dssdc
dcc
vasdcr player = {
x:1dsc0,
y:10,d
width:cd20,
height:2cds0,
color:'red'csc
}wec
2e
wicndow.onload = function init() {
2c // called AFTER the page has been loaded
c2anvas = document.querySelector("#myCanvas");
ce2c
//2e often useful
w = e2canvas.width;
h = cacnvas.height;
2ce2c
// 2ecimportant, we will draw with this object
ctx = e2canvas.getContext('2d');
ce2
/ce2c/ ready to go !
mainLrvoop();
};bdb
vsdf
funcvsdtion mainLoop() {
// 1 fv- clear the canvas
ctx.cledfbvarRect(0, 0, w, h);
fgn
// yrgndraw the ball and the player
drawFileledRectangle(player);
drawFillbtedCircle(ball);
gre
/fb/ animate the ball that is bouncing all over the walls
movegeBall(ball);
3g
//34rg ask for a new animation frame
requesettAnimationFrame(mainLoop);
}gethw
yjk
funryikction moveBall(b) {
b.x +f= b.speedX;
b.y +=jyr b.speedY;
uryfk
testCyjfollisionBallWithWalls(b);
}f
hmjh
funryikctiontion testCollisionBallWithWalls(b) {
// COLLIgtSION WITH VERTICAL WALLS ?
if((b.x + fb.radius) > w) {
// the ballgf hit the right wall
// change horgizontal direction
b.speedX = -b.fspeedX;
gw
//efg put the ball at the collision point
b.x =wefg w - b.radius;
} else if((eqb.x -b.radius) < 0) {
// the ballfgw hit the left wall
// change horiefgzontal direction
b.speedX = -b.speweedX;
fgw
// efgput the ball at the collision point
b.x = wefb.radius;
}gwefg
wefgwe
// COLfgwLISIONS WTH HORIZONTAL WALLS ?
// Not inefg the else as the ball can touch both
// vertical wefand horizontal walls in corners
if((b.y + b.radgwius) > h) {
// the ball hitefg the right wall
// change horizontwefal direction
b.speedY = -b.speedY;gwefg
wefgwe
// putfg the ball at the collision point
b.y = h wefgwef- b.radius;
} else if((b.y -bgw.radius) < 0) {
// the ball hit tefghe left wall
// change horizontalwef direction
b.speedY = -b.speedY;gwefg
wefgwefgw
// put thefge ball at the collision point
b.Y = b.radieus;
} fgw
}efgwef
g53
fungrction drawFilledRectangle(r) {
/fg/ GOOD practice: save the context, use 2D trasnformations
ctxg.save();
fgf
/gf/ translate the coordinate system, draw relative to it
ctxgf.translate(r.x, r.y);
gfg
cftx.fillStyle = r.color;
//gf (0, 0) is the top left corner of the monster.
ctx.gfillRect(0, 0, r.width, r.height);
jh
jhj// GOOD practice: restore the context
ctxhj.restore();
}hmn

funchntion drawFilledCircle(c) {
//hn GOOD practice: save the context, use 2D trasnformations
ctx.hnsave();
hnh
/nh/ translate the coordinate system, draw relative to it
ctxnhn.translate(c.x, c.y);
hnh
cnhntx.fillStyle = c.color;
// (hn0, 0) is the top left corner of the monster.
ctx.behnginPath();
ctx.arc(h0, 0, c.radius, 0, 2*Math.PI);
ctx.fill(nh);
nhn
hn// GOOD practice: restore the context
cthnx.restore();
}egfbefgwerfgwefg

You might also like