JavaScript: Intro to Web Game Development – Part 3: add graphical components

Continuing the series on how to create a web browser game of Pong using JavaScript, this post will show how to add some graphical components to the game, such as the right and left paddles, ball, net and score placeholders. Part 2 is here:

JavaScript: Intro to Web Game Development – Part 2: canvasContext with rounded corners

Step 1: Draw the net

Here is a function to draw the net, placed outside of the window.onload function:

function drawNet() {
    for(var i = 0; i < canvas_height; i += 30) {
        canvasContext.fillStyle = 'white';
	canvasContext.fillRect(canvas_width/2, i, 2, 10, 'white');

The middle of the screen is found at canvas_width/2. i += 30 is what causes the spaces between the dashes.

Then simply call the function from inside the window.onload function:


Step 2: Draw the right and left paddles

Here is some code, placed inside the window.onload function, that will create the paddles (placed statically for now):

// Left paddle
canvasContext.fillStyle = 'white';
canvasContext.fillRect(30, 50, 10, 70);

// Right paddle
canvasContext.fillStyle = 'white';
canvasContext.fillRect(canvas_width-40, canvas_height-120, 10, 70);

Step 3: Draw the ball

For now, I will just draw the ball as a 10 x 10 square:

// Draw the ball
canvasContext.fillStyle = 'white';
canvasContext.fillRect(200, 300, 10, 10);

Step 4: Draw the placeholders for the scores

I want these at the top of the canvas, on the left and right side of the net:

// Place holder for the scores
canvasContext.font="40px monospace";
canvasContext.fillText("1", (canvas_width/2)-60, 40);
canvasContext.fillText("0", (canvas_width/2)+35, 40);

Here is what the canvas looks like so far: