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>

 

Tags:



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