有这个代码:
$(window).on('load resize', function() {
initContainer();
});
$(window).scroll(function(){
setMotionPath();
});
function initContainer() {
var element = $('.svg');
var motionPath = MorphSVGPlugin.pathDataToBezier("#way").reverse();
TweenLite.set("#circle", { transformOrigin: "50% 50%" });
setMotionPath();
};
function setMotionPath() {
var element = $('.svg');
var motionPath = MorphSVGPlugin.pathDataToBezier("#way").reverse();
TweenLite.to("#circle", 0, {
x: motionPath["x"],
y: motionPath["y"]
});
};
#circle {
transform-origin: 0px 0px 0px;
}
html,
body {
height: 200%;
width: 100%;
margin: 0;
padding: 0;
}
svg {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/MorphSVGPlugin.min.js"></script>
<svg class="svg" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">
<path id="way" stroke="#000" stroke-dasharray="4,2" stroke-width="1" d="M 100,10 L 100,30 L 100,50 L 100,70 L 100,90 L 100,110 L 100,130 L 100,150 L 100,170 L 100,190 L 100,210 L 100,230 L 100,250 L 100,270 L 100,290 L 100,310"></path>
<circle cx="100" cy="30" r="20" stroke="black" stroke-width="1" fill="orange" id="circle"/>
</svg>
问题:如何让圆path在滚动时沿路径平滑移动(最好使用 TweenMax)?
PS:路径path可以任意,以直线为例,可以这样:
<path id="pPath"
d="m782.19032,61.21567c-5.10542,4.08434 -38.80117,92.91857 -108.23481,123.55105c-69.43365,30.63249 -187.87928,-10.21082 -178.68954,-76.58122c9.18974,-66.37041 135.80405,-60.24388 138.86731,8.16868c3.06326,68.41254 -36.759,102.1083 -107.21373,120.48779c-70.45474,18.37948 -128.9788,10.90961 -163.64275,0.48347c-34.66395,-10.42613 -110.54388,-54.17155 -159.01952,-99.52852"
stroke-dasharray="5 2"
stroke-width="2"
stroke="#000"
fill="transparent"/>

这是更新的答案。这正是你想要的。
我将尝试大致解释它是什么以及它是如何工作的。
motionPath是一个包含直线坐标的数组,但它包含的不是逐个像素的所有坐标。并将线分成几段,为每段选择坐标(中心)。当您TweenLite.to通过该方法设置一对坐标时,动画到达并停止。但是如果你每次滚动都尝试给新的坐标,那么动画就不会流畅,因为当你没有完成路径的第一部分就滚动时,圆圈已经接收到新的坐标并跟随它们(离开线)。还有第二种选择。我们立即为该方法提供一个坐标数组,
TweenLite.to并将动画标识符存储在一个变量tween = TweenLite.to........中。之后,我们就可以操作动画了(例如,暂停)。还有更重要的一点,tween它已经有了一个方法progress(),它的值可以从0到1。如果我们设置了一个中间进度,那么动画就会返回到它。我们就是这样做的,设置每个滚动的进度,并立即暂停动画。
这是我们的预期结果。
对于一条直线。
这里不需要
reverse坐标。这个插件有很多选择。你可以亲眼看到这一切。