How to move an object on the HTML5 canvas

This topic explains how to draw a shape on the canvas and how to move this shape. This topic includes the demo and the complete code with explanation.

First you can see the demo in the below section. You move the car shape in forward and backward with Right and left arrow keys of the keyboard. Show press the Right and left to run the car:

Demo (Press Right and left arrow keys)

See Also Text Animation in HTML 5

Canvas code( using getImageData() and putImageData() methods)

<!DOCTYPE html>
<html>
    <head>
    <title>Move Car In HTML5</title>
    <!-- Written by Hirndra sisodiya  for the authorcode.com-->
 
    <script type="text/javascript">
        var myImage = new Image();
        var back = new Image();
        var ctx;
        function displayImage() {
            canvas = document.getElementById("myCanvas");
            if (canvas.getContext) {
                ctx = canvas.getContext("2d");
                window.addEventListener('keydown', moveobj, true);
 
                ctx.beginPath();
                ctx.moveTo(25, 150);
                ctx.lineTo(145, 150);
                ctx.lineTo(145, 135);
                ctx.lineTo(115, 130);
                ctx.lineTo(115, 120);
                ctx.lineTo(115, 120);
                ctx.lineTo(50, 120);
                ctx.lineTo(50, 130);
                ctx.lineTo(50, 130);
                ctx.lineTo(40, 130);
                ctx.closePath();
                ctx.fillStyle = "#FF0000";
                ctx.fill();
 
                ctx.beginPath();
                ctx.arc(50, 150, 10, 360, true);
                ctx.fillStyle = "#696969";
                ctx.fill();
 
                ctx.beginPath();
                ctx.arc(110, 150, 10, 360, true);
                ctx.fillStyle = "#696969";
                ctx.fill();
                back = ctx.getImageData(25, 50, 200, 150);
            }
        }
 
          var old = new Image();
          var next = 35;
          function moveobj(evt) {
              switch (evt.keyCode) {
                  case 37:
                      if (next < 20) {
                          return;
                      }
                      next = next - 5;
                      break;
                  case 39:
                      if (next > 650) {
                          return;
                      }
                      next = next + 5;
                      break;
              }
              ctx.fillStyle = "#ffffff";
              ctx.rect(0, 5, 650, 300);
              ctx.fill();
              ctx.putImageData(back, next, 50);
          }
       </script>
  </head>
    <body onload="displayImage()">
       <canvas id="myCanvas" width="650px" height="400px">
    </canvas>
      </body>
</html>

 

Code discussion

 

First we create the car’s upper body with the help of lineto() method and fill with red color, then create the two circle and fill the black color for the car’s wheels.
 
We register the key press event with the help of the following statement in java script:
window.addEventListener('keydown', moveobj, true);
When user will press right or left arrow then function moveobj() will be called that will be set the new position of the car.
 
run car demo
 
When you load the page it will draw the car and it will move 5 pixel right and -5 pixel left direction on the keypress of Right and left arrow respectively.

 

Another way by using save(), translate() and restore() methods)

 

<!DOCTYPE html>
<html><head>
    <title>Move Car In HTML5</title>
    <!-- Written by Hirndra sisodiya  for the authorcode.com-->
 
    <script type="text/javascript">
        var myImage = new Image();
        var back = new Image();
        var ctx;
        function displayImage() {
            canvas = document.getElementById("myCanvas");
            if (canvas.getContext) {
                ctx = canvas.getContext("2d");
                window.addEventListener('keydown', moveobj, true);
 
                ctx.beginPath();
                ctx.moveTo(25, 150);
                ctx.lineTo(145, 150);
                ctx.lineTo(145, 135);
                ctx.lineTo(115, 130);
                ctx.lineTo(115, 120);
                ctx.lineTo(115, 120);
                ctx.lineTo(50, 120);
                ctx.lineTo(50, 130);
                ctx.lineTo(50, 130);
                ctx.lineTo(40, 130);
                ctx.closePath();
                ctx.fillStyle = "#FF0000";
                ctx.fill();
 
                ctx.beginPath();
                ctx.arc(50, 150, 10, 360, true);
                ctx.fillStyle = "#696969";
                ctx.fill();
 
                ctx.beginPath();
                ctx.arc(110, 150, 10, 360, true);
                ctx.fillStyle = "#696969";
                ctx.fill();
            }
        }
 
        var old = new Image();
        var next = 0;
        function moveobj(evt) {
            ctx.fillStyle = "#ffffff";
            ctx.rect(20, 5, 600, 300);
            ctx.fill();
            switch (evt.keyCode) {
                case 37:
                    ctx.restore();
                    displayImage();
                    break;
                case 39:
                    ctx.save();
                    ctx.translate(5, 0);
                    displayImage();
                    break;
            }
        }
        function clickhere() {
            document.getElementById("span").innerHTML = "Use the right and left arrow keys";
        }
       </script>
  </head>
    <body onload="displayImage()">
<input id="Button1" type="button" value="Start the car" align="center" onclick="clickhere();">
<span id="span"></span><br>
       <canvas id="myCanvas" width="600px" height="330px">
    </canvas>
 
</body></html>
  • Alistair

    You might find that pushing the context onto a stack quicker to redraw than put image data. Ie: ctx.save(); ctx.translate(next,y); [draw code]; ctx.restore();

    • Thank you Alistair

      I have updated the article with another way as you suggested. In first look it seems that it is better to use the translate method for moving object.

      Could you please review the code…

      • puneeth

        i am using the second method but not able to move to forward, if i press forward key then image will not be reload. please rectify

        • hi puneeth
          I have checked the second code snippet twice But i have not any problem to move forward the object on -> key press.

          please check again.

          thanks

  • pembicara khusus internet

    terima kasih karena sudah memberikan informasi yang sangat
    bermanfaat dan sukses selalu