JavaScript Tutorial – Move an Image using the Arrow Keys in HTML Canvas

We are moving on from animating the object on its own to now moving it with the arrow keys on the keyboard. In this tutorial we will demonstrate how to add key down and up events to the HTML Canvas and move an image in that direction. Animating objects and moving them inside of a game is the most important part of any games design, JavaScript makes it a lot easier to create objects and move them using their x and y coordinates inside of HTML and you can see the results directly in the web browser. We will be using Only HTML CSS and JavaScript in this tutorial to create this project. Once we have a good fundamental understanding of the project and how to work with the sprites properly we can move on to adding more interactions such as object collision and Sprite animations.

Lesson Objectives –

  1. Create a simple project to move an image using the arrow keys on the keyboard
  2. Use key down and key up events to register the user inputs
  3. Use HTML Canvas to animate the object in the right direction
  4. Dynamically load the images to the canvas and animate it using the request animation frame event
  5. Work with various data types such as variable object, string, boolean and integer
  6. Identify the keys needed for this project and code them in the update function

Video Tutorial

 

Download the images here

 

Source Code –

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Move Sprite Image with keyboard MOO ICT</title>
    <style>
        body
        {
            background-color: #646464;
            text-align: center;
        }
        canvas
        {
            background: url("grass.png") no-repeat;
            background-size: cover;
            border: 2px solid black;
        }
    </style>
</head>
<body>
    <h1>Move a Sprite Image with Keyboard MOO ICT</h1>
    <canvas width="500" height="400"></canvas>

    <script>
        var canvas = document.querySelector("canvas");
        var drawingSurface = canvas.getContext("2d");

        var spriteObject = 
        {
            x:0,
            y:0,
            width:64,
            height:64
        };

        var moo = Object.create(spriteObject);
        moo.x = 100;    
        moo.y = 100;
        var image = new Image();
        image.addEventListener("load", loadHandler, false);
        image.src = "moo.png";
        var Xspeed = 0;
        var Yspeed = 0;
        var moveLeft = false;
        var moveRight = false;
        var moveUp = false;
        var moveDown = false;

        window.addEventListener("keydown", function(e)
        {
            switch(e.key)
            {
                case "ArrowUp":
                    moveUp = true;
                    break;
                case "ArrowDown":
                    moveDown = true;
                    break;
                case "ArrowLeft":
                    moveLeft = true;
                    break;
                case "ArrowRight":
                    moveRight = true;
                    break;
            }
        }, false);

        window.addEventListener("keyup", function(e)
        {
            switch(e.key)
            {
                case "ArrowUp":
                    moveUp = false;
                    break;
                case "ArrowDown":
                    moveDown = false;
                    break;
                case "ArrowLeft":
                    moveLeft = false;
                    break;
                case "ArrowRight":
                    moveRight = false;
                    break;
            }
        }, false);

        function loadHandler()
        {
            update();
        }

        function update()
        {
            // create the animation loop
            window.requestAnimationFrame(update, canvas);
            moo.x += Xspeed;
            moo.y += Yspeed;

            if(moveUp && !moveDown)
            {
                Yspeed = -5;
            }
            if(moveDown && !moveUp)
            {
                Yspeed = 5;
            }
            if(moveLeft && !moveRight)
            {
                Xspeed = -5;
            }
            if(moveRight && !moveLeft)
            {
                Xspeed = 5;
            }
            if(!moveUp && !moveDown)
            {
                Yspeed = 0;
            }
            if(!moveLeft && !moveRight)
            {
                Xspeed = 0;
            }
            if(moo.x < 0)
            {
                moo.x = 0;
            }
            if(moo.y < 0)
            {
                moo.y = 0;
            }
            if(moo.x + moo.width > canvas.width)
            {
                moo.x = canvas.width- moo.width;
            }
            if(moo.y + moo.height > canvas.height)
            {
                moo.y = canvas.height - moo.height;
            }

            render();
        }

        function render()
        {
            drawingSurface.clearRect(0,0, canvas.width, canvas.height);

            drawingSurface.drawImage(
            
            image, 
            Math.floor(moo.x), Math.floor(moo.y),
            moo.height, moo.width
            );
        }

    </script>
</body>
</html>

Source Code Explained further:

Variable Declarations:

var canvas = document.querySelector(“canvas”);: This line selects the canvas element from the HTML document and assigns it to the variable canvas.
var drawingSurface = canvas.getContext(“2d”);: This line gets the 2D rendering context for the canvas, allowing us to draw graphics on it, and assigns it to the variable drawingSurface.
var spriteObject = { x:0, y:0, width:64, height:64 };: This defines an object called spriteObject representing the sprite’s properties: initial position (x and y coordinates) and size (width and height).

Initialization:

var moo = Object.create(spriteObject);: This creates a new object moo based on the spriteObject prototype and initializes it with default properties.
moo.x = 100; moo.y = 100;: This sets the initial position of the sprite to (100, 100).

Loading Image:

var image = new Image();: This creates a new Image object.
image.addEventListener(“load”, loadHandler, false);: This adds an event listener to the image object that listens for the “load” event and calls the loadHandler function when the image is loaded.
image.src = “moo.png”;: This sets the source of the image to “moo.png”.

Event Listeners:

window.addEventListener(“keydown”, function(e) { … }, false);: This adds an event listener to the window that listens for keydown events (when a key is pressed) and triggers the provided function. It sets boolean variables (moveUp, moveDown, moveLeft, moveRight) based on the arrow keys pressed.
window.addEventListener(“keyup”, function(e) { … }, false);: This adds an event listener to the window that listens for keyup events (when a key is released) and triggers the provided function. It resets the boolean variables when the arrow keys are released.

Animation Loop and Update Function:

function loadHandler() { update(); }: This function is called when the image is loaded. It calls the update() function.
function update() { … }: This function is the main update loop of the game. It is called recursively using window.requestAnimationFrame to create a smooth animation. It updates the sprite’s position based on user input and handles collision detection with the canvas boundaries.

Rendering Function:

function render() { … }: This function clears the canvas and draws the sprite image at its current position using drawingSurface.drawImage.

Overall, this JavaScript code sets up an interactive environment where users can control the movement of a sprite image within a canvas element using keyboard input. The sprite moves smoothly in response to arrow key presses and is constrained within the boundaries of the canvas.

Tags:



2 responses to “JavaScript Tutorial – Move an Image using the Arrow Keys in HTML Canvas”

  1. Bob says:

    moo.x= 100 and moo.y= 100, please explain, I don’t understand this section

  2. MOO ICT says:

    MOO is a sprite object we have created in the tutorial. That has x and y properties inside of it. We are using the JavaScript Object as a foundation to include these properties into a custom object in this case the moo sprite. To move the sprite up, down, left and right we need to modify the x and y values. by default we set both of these values to 100 so when the app is loaded in the browser it will display the moo sprite 100 pixels in the x direction and 100 pixels in the y direction. Hope this helps.

Comment on this tutorial and let us know how you got on -