【发布时间】:2017-11-14 19:07:05
【问题描述】:
我正在根据我的滚动位置为 SVG 线条制作动画。它可以工作,但 FPS 非常低,动画本身也很滞后。我很确定是我的原生 Javascript 技能搞砸了,但我不知道如何解决它。
我在实际网站上创建了一个快速而肮脏的 JSbin 副本;
http://jsbin.com/vigaqoxiru/edit?html,css,js,output
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}
document.addEventListener('DOMContentLoaded', function() {
Timeline();
});
function Timeline() {
requestAnimationFrame(animateLine)
function convertRange( value, r1, r2 ) {
return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
}
function animateLine() {
var offset = window.scrollY;
var wheight = window.innerHeight;
var timeline = document.querySelector(".Approach--steps");
var theight = timeline.getBoundingClientRect().top - wheight;
if (theight < 0) {
var timelineMin = timeline.offsetHeight;
var objectMin = timeline.offsetTop;
var objectMax = timeline.offsetTop + timeline.offsetHeight;
document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
}
}
window.addEventListener('scroll', function(){
requestAnimationFrame(animateLine)
});
}
正如您所见,它不会以 60fps 的速度滚动,但我使用的是 scale 属性、requestAnimationFrame 和舍入值。知道实现这个动画的更好方法是什么吗?最好没有jQuery。 GSAP 没问题,因为我已经在运行它了。
【问题讨论】:
-
为什么使用 SVG?为什么不用 CSS 使用常规 div 和动画高度?
-
因为现在我只使用一个简单的行来进行演示,但是 svg 稍后会更复杂一些。这只是基础,我将添加一些圈子!
标签: javascript html css svg