【问题标题】:Javascript: How to create a smooth rotation animation for an image? [Compass needle]Javascript:如何为图像创建平滑的旋转动画? [指南针]
【发布时间】:2017-09-05 22:05:26
【问题描述】:

我喜欢为移动设备构建指南针应用。我已经创建了返回罗盘针旋转变化值的函数。 (例如 20)但是如果我只是将 'image-transform' 设置为 'rotate(x deg)' 它看起来有点跳跃,所以我的想法是为针添加一个平滑的动画来移动。


如何编写一个可以为我的指南针添加动画的js函数?

重要提示:使用参数“20”调用函数时会发生什么情况,然后使用不同的参数“-30”再次调用 0.5 秒(当转 20 秒动画尚未结束时)。因此,该功能的一个功能必须是取消正在运行的动画并将新的 change-value('20') 添加到旧的 change-value('-30') 并开始另一个动画。


希望你能理解我的问题。这是我的基本功能:

var change_value=20;
function start_animation(change_value){ 
  $needle_element.css("-webkit-transform", "rotate(" + change_value + "deg)")
}

【问题讨论】:

  • 请出示您正在使用的代码,否则我们真的帮不了您。
  • 改用 CSS 过渡。
  • 我不能使用 CSS 过渡 @ibrahimmahrir。我需要计算动画的旋转值。这在 css 中是不可能的......
  • @jonas00 为什么???
  • 我的代码不会帮助你@ScottMarcus。我已经添加了我的基本功能,但我不得不承认,这就是我所拥有的。

标签: javascript html css animation


【解决方案1】:

这是你要找的吗?

// Get references to DOM elements
var input = document.getElementById("angle");
var btn = document.getElementById("btnGo");
var needle = document.getElementById("needle");

// Set up click event handler
btn.addEventListener("click", start_animation);

// Storage for the previous angle
var lastAngle = "";

function start_animation(){ 
  // Update the total angle needed
  lastAngle = +lastAngle + +input.value;
  
  // For testing:
  console.clear()
  console.log("Current total angle: " + lastAngle);

  // Move the needle:
  needle.style.transform = "rotate(" + lastAngle + "deg)";
}
#needle {
  height:5px;
  background-color:#808080;
  width:100px;
  margin-top:100px;

  /* Initial value for rotate is needed for transition to work */
  transform:rotate(0);  

  /* CSS transition creates smooth effect */
  transition:all 1.5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="angle" value="20"><button type="button" id="btnGo">Go!</button>
<div id="needle"></div>

【讨论】:

  • 感谢您的解决方案。诀窍是这种风格:“transition:all 1.5s;”之后“transform:rotate”将平滑旋转图像。旋转速度可以设置为过渡风格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多