【问题标题】:rotate image continuously with javascript用javascript连续旋转图像
【发布时间】:2021-10-29 02:16:00
【问题描述】:

我想编写一个 javascript 来通过单击一个按钮来连续旋转图像。我可以通过点击进行部分旋转。我认为我应该递归调用该函数以获得连续旋转,但我不知道该怎么做。 以下是我的代码。

<html>
<head>
    <title>Image Rotation</title>
</head>

<body>
        <button id="rotate">Rotate</button>
    <img src="images/circle.png" id="sample" ;" alt="" />
    
</body>

<script>
var rotation = 0;


document.querySelector("#rotate").addEventListener('click', function() {
    
    rotation += 90;

    
    document.querySelector("#sample").style.transform = 'rotate(' + rotation + 'deg)';
});
            
</script>
</html>

【问题讨论】:

标签: javascript rotation


【解决方案1】:

在你的css文件中添加一个类

.rotating {
   animation: rotate 1s infinite;
}

@keyframes rotate {
   from { transform: rotate(0deg); }
   to { transform: rotate(360deg); }
}

然后通过 javascript 将该类添加到您的元素中

document.querySelector("#rotate").addEventListener('click', function() {
   document.querySelector("#sample").classList.add('rotating')
});

【讨论】:

  • 但是为什么359deg
  • 我总是这样做,因为360deg0deg 的旋转量相同。因此,如果您旋转到360deg,您将在完全相同的位置有两个帧,并且看起来它会在一次旋转后卡住一小会儿。 @HaoWu
  • 不,它不会... 0deg360deg 非常适合连续旋转动画。只要定时功能是linear。那为什么是359deg 而不是359.9deg359.99deg
  • @HaoWu 不确定,也许你是对的。我曾经一直这样做,因为我曾经遇到过一个问题,即我有一个旋转卡住的框架,这是我的解决方法。 codepen.io/puerschel93/pen/eYRJZBr 在我的示例中,您实际上看不到任何区别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
相关资源
最近更新 更多