M
M
Michael2018-03-24 14:59:43
css
Michael, 2018-03-24 14:59:43

How to change photo when mouse is moved (js)?

I have a photo of a bike:
5ab63d1bb301a334031699.jpeg
I want to make it rotate by 180 when you click the mouse and move to the left and back, so that the bike changes its angle:
5ab63d6736e10916596340.png5ab63d71ee79a658208299.png5ab63d7eb01ef035087787.png
How it will look in js, at least approximately.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dymok, 2018-03-24
@UnluckySerivelha

Maybe what you need

P
Peter, 2018-03-24
@star52

  1. You need to change the original image. Let at the expense of the src attribute/property.
  2. Since the mouse is being used, we need to handle two of its events, for our img tag:
    1. mousedown - the mouse is held down, the coordinates are remembered (the horizontal axis is enough)
    2. mousemove - check the difference on the horizontal axis, along which you need to "change the angle". If it is reached, we call the image change function (point 3). Don't forget to remove the mousemove handler from our img tag.
      Note: to get the coordinates, you can also work with the container (in which the img tag is located)
      Here is my example:
      JS
      function nextImage(image) {
        var imageNames = ["blackbird.jpg", "duck.jpg", "sheep.jpg"];
        image.current++;
        if (image.current === imageNames.length) image.current = 0;
        image.src = "images/" + imageNames[image.current];
      }
      
      window.onload = function() {
        var img = document.getElementById("main");
        img.current = 1;// создаём новое свойство (счётчик)
        img.onmousedown = function(event) {
          var startX = event.clientX;
          img.onmousemove = function(event) {
              console.log(startX);
              if (startX - event.clientX < -40) {
                nextImage(this);
                this.onmousemove = null;
              }
          };
          return false; //Позволяет избавиться от стадартного обработчика
        }
      }

      HTML
      <!DOCTYPE HTML>
      <html lang=en> 
      <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href=""/>
        <script src="type.js"></script>
      </head>
      <body>
        <img id="main" src="images/duck.jpg">
      </body>
      </html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question