如何在两个方向同时滚动绘制SVG?

时间:2017-05-02 23:07:22

标签: javascript html css svg

似乎无法弄清楚这个“丁字路口”是如何同时向左和向右画,而不是从左到右,然后到右边。

我一直在努力做的事情;

<path class="path" fill="none" stroke="white"  stroke-width="6" id="triangle" d="M 450,50 L 450,200 L350,200 550,200" />

JS-fiddle:https://fiddle.jshell.net/ewf9soax/

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要做的就是对路径定义稍作调整。

d="M 450,50 L 450,200 L350,200
   M 450,50 L 450,200 L550,200"

正如罗伯特所说,我们将路径分成两个L形的子路径。一个向左,一个向右。由于破折号模式适用于各个子路径,而不是整个路径,因此它会自动运行。

您可能希望更新stroke-dasharray长度以补偿子路径现在比原始路径短的事实。

&#13;
&#13;
// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();

// The start position of the drawing
triangle.style.strokeDasharray = length;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;

// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);

function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  var draw = length * scrollpercent;
  
  // Reverse the drawing (when scrolling upwards)
  triangle.style.strokeDashoffset = length - draw;
}
&#13;
body {
  height: 2000px;
  background: #f1f1f1;
}

#mySVG {
  position: fixed;
  top: 0:;
  width: 900px;
  height: 810px;
  margin-left:-450px;background-color:green;left: 50%;z-index: 100000;
}
&#13;
<svg class ="path" id="mySVG">
  <path class="path" fill="none" stroke="white"  stroke-width="6" id="triangle" d="M 450,50 L 450,200 L350,200
                                                                                   M 450,50 L 450,200 L550,200" />


  Sorry, your browser does not support inline SVG.
</svg>
&#13;
&#13;
&#13;

Updated fiddle