如何在Javascript中旋转图片? [英] How to rotate Image in Javascript?

查看:385
本文介绍了如何在Javascript中旋转图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to rotate fan image when click the turnOn button. And the turnOff button is clicked, rotation is stopped.

我的代码是:

<!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>

推荐答案

尝试一下(由于某种原因,图像未显示):

Try this (for some reason the image is not showing up):

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>

这篇关于如何在Javascript中旋转图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆