Home » Tutorials » Game Development » HTML5 Canvas For Absolute Beginners – Part 5

HTML5 Canvas For Absolute Beginners – Part 5

HTML5 Canvas For Absolute Beginners – Part 5

Welcome to the part 5 of the ‘HTML5 Canvas for Absolute Beginners’. In this tutorial, we will describe the keyboard events in canvas. If you haven’t already, be sure to read the previous articles of this series first!

The idea

In this tutorial, we are going to add in some interactivity into a ball by modifying the code that we have been wrote in the previous tutorial. We will enable the keyboard events in canvas and move the ball according to the arrow keys on keyboard.

HTML5 Canvas Keyboard Events

HTML Structure

Please open up the HTML document that you have done last week, and your document HTML structure should look like below. Note: Please ignore the JavaScript section that exist in your document at this moment, BUT don’t delete it, we will look into it later.

<!DOCTYPE html>
<html>
	<head>
		<title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
	</head>
	<body>
		<canvas id="myCanvas" width="568" height="262">
			<!-- Insert fallback content here -->
            Sorry, your browser doesn't support canvas technology
		</canvas>
	</body>
</html>

JavaScript

In order to enable interaction with the ball that drawn by canvas, there are few things we need to add and change from the JavaScript section in previous document. First of all, we need to remove ‘bounce animation’ by changing the ‘mx‘ and ‘mv‘ values to zero as shown below:

var mx = 0;
var my = 0;

Second, we re-position the ball at the centre of the canvas by changing the values of ‘x‘ and ‘y‘ as shown below:

var x = 284;
var y = 130;

Save your document and preview it. Now you should see a static ball located at the centre of canvas.

Ok, we have remove all animation that has been done in previous tutorial, let’s start to add keyboard events to our canvas object. In order to interact with canvas object via keyboard, first thing we need to do is to declare an event handler for the keydown event in the ‘init()‘ function.

window.onkeydown = keydownControl;

Next, write a function called ‘keydownControl()‘ to handle the keydown event. This function is called whenever a key is pressed and every keys on keyboard has their own key code. In this case, we are using only 4 keys, which is Left Arrow(Keycode: 37), Up Arrow(Keycode: 38), Right Arrow(Keycode: 39) and Down Arrow(Keycode: 40).

function keydownControl(e) {    
	if(e.keyCode==37) {           
		mx = -2;            
		my = 0;
    } else
	if (e.keyCode==38) {
		mx = 0;
        my = -2;
    } else if
	(e.keyCode==39) {
        mx = 2;
        my = 0;
    } else
	if (e.keyCode==40) {
        mx = 0;
		my = 2;
    }
}

Save and run your file, you should able to interact with the ball by using arrow keys 🙂

Final Code

<!DOCTYPE html>
    <head>
        <title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
    </head>
 
    <body>
        <canvas id="myCanvas" width="568" height="262">
            <!-- Insert fallback content here -->
            Sorry, your browser doesn't support canvas technology
        </canvas>
 
        <script type="text/javascript">
            var canvas;
            var ctx;
            var x = 284;
            var y = 130;
            var mx = 0;
            var my = 0;
            var WIDTH = 568;
            var HEIGHT = 262;
 
			function circle(x,y,r) {
			  ctx.beginPath();
			  ctx.arc(x, y, r, 0, Math.PI*2, true);
			  ctx.fill();
			}
			 
			function clear() {
			  ctx.clearRect(0, 0, WIDTH, HEIGHT);
			}
			 
			function init() {
			  canvas = document.getElementById("myCanvas");
			  ctx = canvas.getContext("2d");
			  window.onkeydown = keydownControl;
			  return setInterval(draw, 10);
			}
			 
			function draw() {
			  clear();
			  circle(x, y, 20);
			 
			  if (x + mx > WIDTH || x + mx < 0)
				mx = -mx;
			  if (y + my > HEIGHT || y + my < 0)
				my = -my;
			 
			  x += mx;
			  y += my;
			 
			}
			 
			function keydownControl(e) {
				if(e.keyCode==37) {
					mx = -2;
					my = 0;
				} else
				if (e.keyCode==38) {
					mx = 0;
					my = -2;
				} else if
				(e.keyCode==39) {
					mx = 2;
					my = 0;
				} else
				if (e.keyCode==40) {
					mx = 0;
					my = 2;
				}
			}
			 
			init();
 
        </script>
        </body>
</html>

In next tutorial, we will describe more HTML5 canvas related information. Stay tune!


  • Jonathan

    love your 5 tutorials i thing to add

    else if(e.keyCode == 27)
    {
    mx = 0;
    my = 0;
    }

    this will stop the ball on esc

    • Hi Jonathan,

      Thanks for your suggestion. It’s really a good idea. We really appreciate all web designers and developers gather here and share out their thought and idea.

      Stay in touch with us 🙂

      Regards,
      The Management of onlyWebPro.com

  • sakthivel

    For manual animation of ball we can alter the code as follow:

    function init()
    {
    ctx= document.getElementById(‘mycanvas’).getContext(‘2d’);
    draw();
    window.onkeydown = keydownControl;
    /*return setInterval(draw,10); */remove this line
    }

    function keydownControl(e)
    {
    draw(); // call this functiion here to animate manually

    if(e.keyCode==37)
    {
    mx=-2;
    my=0;
    }

    .

    .
    .

    .

    }

    It wil cause a manual animation…

    • Thank you for sharing! 🙂 Your sharing is highly appreciated.

Android, iOS Development Tutorials