如何在Javascript中旋转图片?

时间:2018-07-04 07:01:49

标签: javascript image rotation

我想在单击打开按钮时旋转风扇图像。 然后单击关闭按钮,旋转停止。

我的代码是:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Test</title>
</head>

<body>

  <img id="myFan" src="fan.png" width="200" heigh="100"><br>
  <button onclick="turnOn()"> On </button><br>
  <button onclick="turnOff()"> Off </button>

  <script>
    function turnOn() {
      var x = document.getElementById("myFan");
    }

    function turnOff() {
      var x = document.getElementById("myFan");
    }
  </script>
</body>

</html>

3 个答案:

答案 0 :(得分:1)

尝试一下(由于某种原因,图片没有显示出来):

let timer;
let turn = 0;
function turnOn() {
  timer = setInterval(turnFan, 200);
  let x = document.getElementById("on");
  x.disabled = true;
}

function turnOff() {
  clearInterval(timer);
  let x = document.getElementById("on");
  x.disabled = false;
}

function turnFan() {
  let x = document.getElementById("myFan");
  turn += 60;
  x.style.transform = "rotate("+ (turn % 360) +"deg)"
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Test</title>
</head>

<body>

  <img id="myFan" src="http://www.pngmart.com/files/7/Ceiling-Fan-PNG-Transparent-Image.png" width="200" heigh="100"><br>
  <button id="on" onclick="turnOn()"> On </button><br>
  <button id="off" onclick="turnOff()"> Off </button>

  
</body>

</html>

答案 1 :(得分:0)

on.addEventListener('click', () => rotateMe.classList.add('rotate'))
off.addEventListener('click', () => rotateMe.classList.remove('rotate'))
img {
  width: 90px;
  height: 90px;
}

.rotate {
  animation: rotate 0.5s infinite linear;
}

@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}
<img src='https://picsum.photos/400/400/?random' id='rotateMe'/>
<button id='on'>On</button>
<button id='off'>Off</button>

答案 2 :(得分:0)

我已经在我的一个项目中实现了这一点:

function rotate90 (img){
var img=this

if (img.style.transform == ""){var x=90;
    window.localStorage.setItem("x", Number(x))  
}

else{
    var x = Number(window.localStorage.getItem("x"))
    x += 90;
    if (x==360){x=0}
    window.localStorage.setItem("x", Number(x))  
    }
img.style.transform ="rotate("+x+"deg)";

                    }

在您的代码中使用img.onclick=rotate90;应该可以。