如何一次滚动绘制每个SVG路径(按时间顺序)?

这与此前的post有关。 但是,我认为这是一项重大任务。 所以我把它分解成更小的块。

我制作了一个简单的SVG图像,其中包含一个“路径”和一个“矩形”元素。 用户可以通过向上和向下滚动页面来打开和关闭窗口(向下滚动页面以打开和关闭页面以关闭/“展开”。但是,两个元素同时“绘制”/动画。我想要做的是当用户向下滚动页面,线条路径绘制,然后“rect”元素绘制(后),所以它更流畅和按时间顺序。

    the single line   svg { position: fixed; margin: auto; top: 0; left: 0; right: 0; bottom: 0; width: 50%; } /*.line{ stroke-dashoffset:850; stroke-dasharray: 850; } .box { stroke-dashoffset:1852; stroke-dasharray: 1852; }*/ .all{ stroke-dashoffset:2702; stroke-dasharray: 2702; } .straightLine { height: 3000px; position: relative; width: 360px; margin: 40vh auto 0 auto; }     
.st0{fill:none;stroke:#000000;stroke-width:8;stroke-miterlimit:10;}
$(document).ready(function() { //variable for the 'stroke-dashoffset' unit var $dashOffset = $(".all").css("stroke-dashoffset"); //on a scroll event - execute function $(window).scroll(function() { //calculate how far down the page the user is var $percentageComplete = (($(window).scrollTop() / ($("html").height() - $(window).height())) * 100); //convert dashoffset pixel value to interger var $newUnit = parseInt($dashOffset, 10); //get the value to be subtracted from the 'stroke-dashoffset' var $offsetUnit = $percentageComplete * ($newUnit / 100); //set the new value of the dashoffset to create the drawing effect $(".all").css("stroke-dashoffset", $newUnit - $offsetUnit); }); });

这怎么样? 您可以通过在scrollBehaviour数组中设置startPctendPct百分比值来控制每个路径的开始时间并完成绘制。

注意:此代码假定您仅使用路径和rects。 如果您开始使用其他元素,则必须更新calcPathLength()函数。

 var scrollBehaviour = [ {id: 'line1', startPct: 0, endPct: 30}, {id: 'rect1', startPct: 30, endPct: 60}, {id: 'line2', startPct: 60, endPct: 80}, {id: 'circ1', startPct: 80, endPct: 100} ]; $(document).ready(function() { // On a scroll event - execute function $(window).scroll(scrollEventHandler); // Call the scroll event handler once at the start to initialise the dash offsets scrollEventHandler(); }); function scrollEventHandler() { // Calculate how far down the page the user is var percentOfScroll = (($(window).scrollTop() / ($("html").height() - $(window).height())) * 100); // For each lement that is getting drawn... for (var i=0; i 
 svg { position: fixed; margin: auto; top: 0; left: 0; right: 0; bottom: 0; width: 50%; } /*.line{ stroke-dashoffset:850; stroke-dasharray: 850; } .box { stroke-dashoffset:1852; stroke-dasharray: 1852; } .all{ stroke-dashoffset:2702; stroke-dasharray: 2702; }*/ .straightLine { height: 3000px; position: relative; width: 360px; margin: 40vh auto 0 auto; }