Move Image with Keyboard Controls | نقل الصورة باستخدام لوحة المفاتيح

Posted by

<!DOCTYPE html>

Move Image using Keyboard

#36 Move Image using Keyboard | تحريك الصورة باستخدام لوحة المفاتيح

In this tutorial, we will learn how to move an image using keyboard keys. This can be a fun and interactive way to navigate through images or create a game.

HTML Code:

  <div id="container">
    <img src="image.jpg" id="image" style="position: absolute; top: 0; left: 0;">
  </div>

JavaScript Code:

  <script>
    const image = document.getElementById("image");
    let topPosition = 0;
    let leftPosition = 0;

    document.addEventListener("keydown", function(event) {
      switch(event.key) {
        case "ArrowUp":
          topPosition -= 10;
          break;
        case "ArrowDown":
          topPosition += 10;
          break;
        case "ArrowLeft":
          leftPosition -= 10;
          break;
        case "ArrowRight":
          leftPosition += 10;
          break;
      }

      image.style.top = `${topPosition}px`;
      image.style.left = `${leftPosition}px`;
    });
  </script>

With this code, we have created a simple HTML page with an image that can be moved using the arrow keys on the keyboard. The image will move 10 pixels in the respective direction each time a key is pressed.

This can be further customized by adding boundaries for the image or changing the speed at which it moves. The possibilities are endless!

Try this out on your own and see how you can incorporate keyboard controls into your web projects.