javascript如何在滚动上移动路径上的元素
作者:互联网
我有一条像垂直蛇一样的路线. (像这个http://www.my-favorite-coloring.net/Images/Large/Animals-Reptiles-Snake-31371.png)
如何在滚动时按X和Y位置移动路径上的元素(圆圈10×10)?
Horizonal还可以:
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' });
};
});
但是我如何沿着路线顺利移动它?
解决方法:
我建议使用矢量(SVG)库,即raphael.js作为动画部分.
在raphael.js中,您可以定义路径,然后沿该路径的长度为任何对象设置动画.
请参阅示例和相应的stackoverflow线程以便更好地理解:
> http://raphaeljs.com/gear.html
> How to animate a Raphael object along a path?
与线程相比,您需要在onScroll事件上附加动画,而不是将其附加到Interval.
编辑:
正如评论者建议的那样,添加link中的相关代码段:
HTML:
<div id="holder"></div>
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
};
更新:
我最近使用pathAnimator执行相同的任务.但要注意性能,复杂的动画可能会非常密集.
标签:javascript,scroll,move,parallax 来源: https://codeday.me/bug/20190517/1120528.html