javascript如何在滚动上移动路径上的元素

Isi*_*sis 5 javascript scroll move parallax

我有一条像垂直蛇一样的路线.(像这样http://www.my-favorite-coloring.net/Images/Large/Animals-Reptiles-Snake-31371.png)

如何在滚动时按X和Y位置移动路径上的元素(圆圈10x10)?

Horizo​​nal还可以:

    var coin = $('#coin');

    $(window).scroll(function(){
        var coinTop = coin.css('top'),
            cointLeft = coin.css('left');

        if($(window).scrollTop() > 100 && $(window).scrollTop() < 600){
            $("#coin").css({ "left":  contLeft + 'px' });
        };
    });
Run Code Online (Sandbox Code Playgroud)

但是我如何沿着路线顺利移动它?

mak*_*ion 6

我建议使用矢量(SVG)库,即raphael.js作为动画部分.

在raphael.js中,您可以定义路径,然后沿该路径的长度为任何对象设置动画.

请参阅示例和相应的stackoverflow线程以便更好地理解:

与线程相比,您需要在onScroll事件上附加动画,而不是将其附加到Interval.

编辑:

正如评论者建议的那样,从链接添加相关的代码段:

HTML:

<div id="holder"></div>
Run Code Online (Sandbox Code Playgroud)

JS:

var e;
var myPath;
var animation;  //make the variables global, so you can access them in the animation function
window.onload = function() {
    var r = Raphael("holder", 620, 420),
        discattr = {
            fill: "#666",
            stroke: "none"
        };
    function curve(x, y, zx, zy, colour) {
        var ax = Math.floor(Math.random() * 200) + x;
        var ay = Math.floor(Math.random() * 200) + (y - 100);
        var bx = Math.floor(Math.random() * 200) + (zx - 200);
        var by = Math.floor(Math.random() * 200) + (zy - 100);
        e = r.image("http://openclipart.org/image/800px/svg_to_png/10310/Odysseus_boy.png", x, y, 10, 10);
        var path = [["M", x, y], ["C", ax, ay, bx, by, zx, zy]];
            myPath = r.path(path).attr({
                stroke: colour,
                "stroke-width": 2,
                "stroke-linecap": "round",
                "stroke-opacity": 0.2
            });
        controls = r.set(
            r.circle(x, y, 5).attr(discattr), r.circle(zx, zy, 5).attr(discattr));
    }
    curve(100,100,200,300,"red");
    animation = window.setInterval("animate()", 10);  //execute the animation function all 10ms (change the value for another speed)
};
var counter = 0;    // a counter that counts animation steps
function animate(){
    if(myPath.getTotalLength() <= counter){   //break as soon as the total length is reached
        clearInterval(animation);
        return;
    }
    var pos = myPath.getPointAtLength(counter);   //get the position (see Raphael docs)
    e.attr({x: pos.x, y: pos.y});  //set the circle position
    counter++; // count the step counter one up
};
Run Code Online (Sandbox Code Playgroud)

更新:

我最近使用pathAnimator执行相同的任务.但要注意性能,复杂的动画可能会非常密集.

  • 很好的答案,几个建议.使这种"平滑"(如@Isis要求)的一种方法是减轻向最终位置的移动.1:使用`requestAnimationFrame`代替间隔以获得最大平滑度.2:像这样计算宽松:`x + =(pos.x - x)*0.2`(改变0.2以满足你的宽松需求) (2认同)