teachers, students, everyone
Tools | Blog | Account | Learn
Login Status

Graphical Javascript for Beginners Part 2
Getting started with Javascript the easy way
Feb 22, 2017

To view part 1, click here. In this tutorial we'll continue with our HTML file and add some new elements to create graphics and animation. In particular, we'll add the HTML 5 Canvas.

Adding A Canvas and adding a Circle T0 The Canvas:

Create a new file in Brackets and name it pong.html

Use link to get the code if it doesn't appear below.... link here. Follow the directions in the comments for placing the code on the page.

Let's review what's in this new code.

  1. add a style tag --> this draws a black border around canvas
  2. create a canvas tag --> this is where the canvas will appear
  3. create a canvas variable using Javascript
  4. add draw method which is where we clear the screen and add graphical elements to the screen
  5. add setInterval which calls the draw method 100 times a second. FYI - If you insert a higher number it will slow down the animation (that is, when we add animation).
  6. draw a Circle. You can place this in the draw method, below what is already there.

When you run your code now you should see a canvas with a grey background and a green circle.

That's how easy it is to add graphics to your HTML page. Next, let's add some animation.


Let's get the circle/ ball to move around the screen and bounce off walls.

Start by creating two new variables at the top of the Script tag below the "canvas" variable. Add the following variables.

var xc = 30;

var yc = 30;

var xSpeed = 5;

var ySpeed = 3;//this is just random

Next, let's change the following line: " ctx.arc(100, 100, 40, 0, Math.PI*2, false);"

change the first "100" to xc and the second to xy.

Next, add the following lines:

xc = xc + xSpeed;

yc = yc + ySpeed;

Now when you run it, the ball should shoot across the screen and go off the right bottom portion of the screen.

To get it to bounce off the walls we need to add some logic to the code using if statements.

if(xc>canvas.width || xc < 0){

  xSpeed = xSpeed * -1;


Do the same thing for yc variable.

Next, we'll a paddle and keystroke and mouse detection to create a pong type game.


No comments posted


Past Posts

Dropbox Public Folder Alternative
Jun 4, 2017

Getting Started with NodeJS
May 1, 2017

Scratch Intro: Racing Game
Jan 15, 2017

Five Best Educational Tools For Teachers
Feb 3, 2017

Coding Gravity
Feb 22, 2017

Drones in Eduction
March 2, 2017

Javascript Intro
April 1, 2017

iPhone Streaming Audio App
April 15, 2017

Installing MySQL
May 15, 2017




Thank You!