Canvas Basics – 03 Moving An Object

This is the third of a series of posts looking at the <canvas> element in HTML5.

I have been using the canvas element to create games and over the next few posts will look at some of the Canvas basics.

This is a follow on from the posts looking at maths in games (click here to read the first post).

If you are not already familiar with HTML, you can read through the posts starting here (click to read).

The first 2 posts in this series can be found at:

  1. Canvas Basics – 01 Hello World
  2. Canvas Basics – 02 Mouse Detection

You can start reading the above links if you have no HTML/Javascript/Canvas experience, or if you have some of the basics covered already, you can continue with this post.

 

What you’ll need

For these posts you will need a text editor (Notepad on Windows for example) and a relatively up to date browser (Google Chrome is my preference).

In the screenshots you are about to see, you will see that I am not using Notepad for coding, this is because I am using a different package which allows you to see line numbers, this will make it easier for me to comment on particular lines.

 

Instructions

If you plan on following all steps in these posts, at this point I would advise setting up a folder to store all the files you will create.

Initially, all files will be saved as “.html” files which by default will open in a web browser.

You will be editing these files in your text editor (for example, right-click the .html file in your folder and choose to open with Notepad) and viewing them in your web browser.

After each step, you might have to save the text editor file and then refresh your web browser to view the changes.

During instructions, I might tell you to save the file and refresh the browser, I will be referring to the line above.

 

Skeleton

If you followed my last post, you should have a skeleton.html file that you are going to start with and build on.

If you don’t have this skeleton file, enter the following code in your text editor and save it as “skeleton.html”.

Image showing basic set up for all future files for canvas basics moving a shape post

<!DOCTYPE html>
<head>
<title>This Is My File</title>
<meta name=”viewport” content=”width=device-width, user-scalable=no”>
<script type=”text/javascript”>

</script>
</head>
<body>

</body>
</html>

For future files, you can open this skeleton and save it as the name instructed and then amend it.

This will be like a template for the basic layout.

The script for Canvas will be entered from line 6 and the Canvas element itself will be entered from line 10,

 

Canvas Basics – Draw A Shape & Move It

This post will draw a rectangle on screen and then you will move it using your keyboard.

The code you are about to see and use is extremely useful when it comes to creating your game.

You have already displayed text on screen, now you are going to create a shape and move it automtically through coded instructions, these are some of the basics of most games.

Let’s Begin

Open your skeleton.html file and save it as “boxmove.html” and then start making the following changes:

  • Line 3 – Change the title of the page to “Moving Boxes”
  • Line 6 – window.addEventListener(‘load’, init, false); as with the last post, we are adding an event listener, when the page loads, then call the “init” function which you will see in later lines.
  • Line 7 – var canvas; as with the last post, we are adding a variable pointing to the canvas
  • Line 8 – var ctx; again, as with the last post, we are adding a variable that will be used later to define the 2d context
  • Lines 9 to 14 – var mybox = { x: 40, y: 50, width: 75, height: 85 } this variable hold the attributes of a box shape we will draw later.  In order it contains the starting X position, starting Y position, width and height of the box.  If I was drawing a standalone box on the canvas I might code this differently, but because we will be later moving this box I find this way easier.  All attributes are contained between the curly brackets { }

 

image showing top of canvas code for canvas basics moving a shape post

Next we will add our init function.

This isn’t too unlike the init function in our last post, this time we are going call our next function “draw”.

Add the following lines:

  • Line 16 – function init(){ this starts our init function.  The function ends with a closing curly bracket.
  • Line 17 – canvas = document.getElementById(“canvas”); this finds the canvas tag later in the html file and sets the canvas variable to reference that tag
  • Line 18 – ctx = canvas.getContext(“2d”); dthis sets the context variable to reference the 2d drawing context of the canvas
  • Line 19 – draw(); this line calls our next function which is called draw
  • Line 20 – } this is the closing bracket ending the init function.

image of init function for canvas basics moving a shape post

 

Next, we enter the draw function which will draw our box on screen.

  • Line 22 – function draw() { this starts our draw function which is called by the init function.  Again, it ends with a closing }
  • Line 23 – ctx.fillRect(mybox.x, mybox.y, mybox.width, mybox.height);  in an earlier post, we displayed “hello world” on screen using fillText, here we are going to create a rectangle using fillRect.  We are assigning the X position, Y position, width and height of our rectangle to be the same attributes of the mybox variable we set earlier.
  • Line 24 – } this closing bracket ends the draw function

image of code for draw function for canvas basics moving a shape post

 

This ends the first part of our script.

Next we add the canvas to the body of the html page.

This code is the same as was used in the last post.

  • Line 29 – <canvas id=”canvas” height=”200″ width=”300″ style=”background-color:green”> this is where we place our canvas on the html document.  This tag is in the body of the page.  You can change the height, width and background color of the canvas.  Save the text file and refresh your browser to see the changes.
  • Line 30 – This browser doesnt support canvas technology, try another or update a user will only see this message if their browser doesn’t support canvas technology.
  • Line 31 – </canvas> this is the closing canvas tag.

image showing last part of canvas code for canvas basics moving a shape post

 

This is how the finished code looks in a browser.

image showing how our canvas code looks in browser for canvas basics moving a shape post

Review

Make changes to the attributes of mybox in lines 10 to 13, save the file in your text editor and refresh your browser to see the changes.

We have put a rectangle on screen, it sits there doing very little, next we will move it.

First we will have the box move on its own to demonstrate the importance of clearing the screen after each frame and then after that we will control the movement using the keyboard.

The full code so far is:

<!DOCTYPE html>
<head>
<title>Moving Boxes</title>
<meta name=”viewport” content=”width=device-width, user-scalable=no”>
<script type=”text/javascript”>
window.addEventListener(‘load’, init, false);
var canvas;
var ctx;
var mybox = {
x: 40,
y: 50,
width: 75,
height: 85
};

function init() {
canvas = document.getElementById(“canvas”);
ctx = canvas.getContext(“2d”);
draw();
}

function draw() {
ctx.fillRect(mybox.x, mybox.y, mybox.width, mybox.height);
}

</script>
</head>
<body>
<canvas id=”canvas” height=”200″ width”300″ style=”background-color:green”>
This browser doesnt support canvas technology, try another or update
</canvas>

</body>
</html>

 

Move The Box Automatically

Save the movebox.html file you have just created as moveboxAuto.html.

Most of the code has already been written, we are going to add a few lines and change some attributes.

  • Line 10 – Change the starting X position to be 10
  • Line 11 – Change the starting Y position to be 10
  • Line 12 – Change the box width to be 25
  • Line 13 – Change the box height to be 35

image of changes to mybox attributes for canvas basics moving a shape post

For the init function, we are going to change it to call a new function called “loop” which we will be creating soon.

  • Line 19 – Change the function being called to the loop function which we are about to create.

change made to init function for canvas basics moving a shape post

We are now going to add 2 new functions.

The first will be an update function, this is what is going to assign a new X position to our box.

The next is a loop function which will call the update function (where a new X position is assigned) and the draw function (which draws the box on screen).

image of new functions in canvas code for canvas basics moving a shape post

 

Continuously assigning a new X position and redrawing the box gives the impression of it being animated.

  • Line 26 – function update() { this starts our update function.  Again, it ends with a closing }
  • Line 27 – mybox.x +=1;  this line takes the current x postion of mybox and adds 1 to it to assign the new x position.
  • Line 28 – } this closing bracket ends the draw function
  • Line 30 – function loop() { this starts our loop function.  Again, it ends with a closing }
  • Line 31 – update();  this line calls our update function which changes the X position of the box
  • Line 32 – draw();  this line calls our draw function which draws the box on screen, the update function will assign a new X position
  • Line 32 – window.requestAnimationFrame(loop);  this line calls the loop function about 60 times a second, so the update and draw functions are
  • Line 34 – } this closing bracket ends the draw function

If you save the text file as it is and refresh your browser you should end up with something like the image below.

image of how our canvas looks so far for canvas basics moving a shape post

It may look like your box is getting wider, it isn’t really.

What is happening is your box is starting at X position 10, then being redrawn at 11, then at 12, then at 13 and so on.

However, we have not yet told the page to delete the box that was on the page so we end up with lots of boxes overlapping.

What we want to happen is draw a box, clear the box and redraw the box in its new position and repeat this so quickly it looks like a moving box to us.

When working on the mouseposition file, you used “ctx.clearRect….” to delete the text that was on screen before showing the new x and y positions of the mouse pointer.  We are going to add the same line to our draw function.

  • Line 23 – ctx.clearRect(0, 0, canvas.width, canvas.height); the clearRect() method clears the pixels of a given rectangle area.  We are going to clear the entire canvas so starting from zero on the X and Y axes we want to go across the width and height of the canvas and delete all pixels in this area before the fillRect() method adds the new box.

image of updated draw function for canvas basics moving a shape post

Review & Try It Yourself

When you save your text file and refresh your browser, you should see you rectangle move across the screen automatically.

Sit back, drink some coffee and read back through this post so far.

Change the mybox attributes, change the update function by amended the value 1 on the x line, or adding a line to update the y position too.

updated update canvas function for canvas basics moving a shape post

If you add line 29, save your file and refresh your browser you should now see the box moving down and to the right.

The code so far is:

<!DOCTYPE html>
<head>
<title>Moving Boxes</title>
<meta name=”viewport” content=”width=device-width, user-scalable=no”>
<script type=”text/javascript”>
window.addEventListener(‘load’, init, false);
var canvas;
var ctx;
var mybox = {
x: 10,
y: 10,
width: 25,
height: 35
};

function init() {
canvas = document.getElementById(“canvas”);
ctx = canvas.getContext(“2d”);
loop();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(mybox.x, mybox.y, mybox.width, mybox.height);
}

function update() {
mybox.x += 1;
mybox.y += 1;
}

function loop() {
update();
draw();
window.requestAnimationFrame(loop);
}

</script>
</head>
<body>
<canvas id=”canvas” height=”200″ width”300″ style=”background-color:green”>
This browser doesnt support canvas technology, try another or update
</canvas>

</body>
</html>

 

In the update function, the value 1 that you change the x and y values by could also be thought of as speed.

If you changed this to 2, then the box would move 2 pixels instead of 1, it looks like it is travelling twice as fast.

However, if you changed it to something like 200 then it may look like it is jumping from spot to spot rather than moving smoothly, because the change in position is too big.

If we were creating a game like tennis, we could use variables instead of 1 on our “mybox.x +=1;” line.

If the ball is travelling at +1 on the x axis (moving right) and it hits the other players racket, we would want our box to now move using “mybox.y -=1;” which is left.

Other variables can be used to increase the speed the ball is hit back at.

If playing the computer you could set the variable to increase as the score increases, so the higher your score the faster the ball moves and the harder the game is.

 

What’s Next?

In the next post we will change things around a bit.

We will create another blank .html file which will reference a .js (javascript) file.

This javascript will contain all our script  instead of the <script>….</script> tags on our current html file.

This is just another way of doing things that I wanted to show you.

Regarding what we will be doing next, we are going to create a box that we can move around using the arrow keys on our keyboard.

 

Disclaimer

I am not claiming that the code that I use in these examples is the best, most efficient and up to date code.  

Code gets updated and improved over time, what is best practice today may not be tomorrow.

email

Comments are closed

Follow

Get every new post delivered to your Inbox

Join other followers:

%d bloggers like this: