[英]Animating a div with requestAnimationFrame
I am trying to animate a div
horizontally first and then vertically. 我试图首先水平动画div
,然后垂直动画。 But the problem using requestAnimationFrame
is that it is doing both animations at once, making the div
travel diagonally. 但是使用requestAnimationFrame
的问题在于它同时执行两个动画,使div
对角移动。
Here is the fiddle link: https://jsfiddle.net/akonchady/z4qmkuyc/22/ 这是小提琴链接: https : //jsfiddle.net/akonchady/z4qmkuyc/22/
What am I doing wrong? 我究竟做错了什么?
Note: It works as expected if I give a timeout for the second invocation as follows: 注意:如果我给第二次调用超时,它按预期工作,如下所示:
animate('abc', 'marginLeft', 250, 1000); setTimeout(function() { animate('abc', 'marginTop', 250, 1000); }, 3000);
However I want to avoid the timeout. 但是我想避免超时。 How can I achieve this just using requestAnimationFrame
? 如何使用requestAnimationFrame
实现这一目标?
Most
functions
in JavaScript are synchronous(will execute sequentially). JavaScript中的大多数functions
都是同步的(将按顺序执行)。 But withasynchronous
functions(which will not wait for earlier function to finish), usecallbacks
to control the flow of the execution. 但是使用asynchronous
函数(不会等待早期函数完成),使用callbacks
来控制执行流程。
To invoke send function
when first one is done with the animation, use callback
要在第一个完成动画时调用发送function
,请使用callback
function animate(id, styleAttr, finalValue, duration, callback) { var ele = document.getElementById('abc'), startTime = +new Date, //Not sure how readable this is ? delta = null, req = null; (function timeout() { elapsedTime = +new Date - startTime; if (elapsedTime >= duration) { cancelAnimationFrame(req); ele.style[styleAttr] = finalValue + 'px'; if (typeof callback !== 'undefined') { callback(); } return; } else { delta = finalValue / duration; ele.style[styleAttr] = delta * elapsedTime + 'px'; } req = requestAnimationFrame(timeout); })(); } animate('abc', 'marginLeft', 250, 1000, function() { animate('abc', 'marginTop', 250, 1000); });
#abc { width: 100px; height: 100px; background-color: red; }
<div id='abc'> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.