我一直在阅读互联网上的指南,但我一直无法找到一种方法来将一条线从一个位置动画到一个新位置。
显然这需要“补间”来创建平滑的动画,并且不是内置的?我所找到的只是“看看这个可以为你处理这个问题的 JavaScript 框架!”
原生 JavaScript(或 jQuery)中是否存在类似于:
animateLine(current, target, duration, easingFunction)
{
move(line.x1, target.x1, duration, easingFunction);
move(line.y1, target.y1, duration, easingFunction);
move(line.x2, target.x2, duration, easingFunction);
move(line.y2, target.y2, duration, easingFunction);
}
我只想迭代一个行数组,在 setInterval()
内部调用 animateLine(lines[i], Targets[i],uration, easingFunction)
.
最佳答案
给这只猫剥皮有很多不同的方法...但是,就逐帧动画而言,您需要 requestAnimationFrame
。该函数调用您传递给它的任何内容,并传递时间戳。然后只需更改这些“线”的属性即可将它们移动到屏幕上。
如果您正在制作 <hr>
的动画元素,您可以使其绝对定位,然后只需更改 top
每帧数量:
html:
<hr id="myLine"/>
CSS:
#myLine { position:absolute; width:100% }
js:
function easeOutQuad(t) { return t*(2-t) };
var startTime = null,
percent, elapsed,
duration = 3000,
end = 400,
hr = document.getElementById('myLine');
function step(timestamp) {
if (startTime === null) startTime = timestamp;
elapsed = timestamp - startTime;
percent = elapsed/duration;
if (elapsed < duration) {
// apply easing fn
percent = easeOutQuad(percent);
var frameDist = end * percent;
hr.style.top = frameDist + 'px';
// next frame
requestAnimationFrame(step);
} else {
// on complete...
}
}
// begin
requestAnimationFrame(step);
这是一个 fiddle :http://jsfiddle.net/oytwdk9s/
如果您想支持 IE9 及更早版本,则需要 polyfill对于 requestAnimationFrame
.
关于javascript - 在 vanilla JS 中制作简单的 2D 线动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029654/