我似乎无法找到一个好的、有效的示例/教程来说明如何绘制一条简单的垂直线,该线在滚动时从无到有逐渐动画化。
我有下面的代码绘制一条水平线,但我似乎无法成功地将其更改为一条继续动画的垂直线。
HTML:
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M1 0 L75 0"/>
</svg>
CSS:
#mySVG {
position: fixed;
top: 15%;
width: 400px;
height: 210px;
margin-left:0px;
}
JS:
<script>
// 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;
}
</script>
最佳答案
这应该只是让你的线垂直的问题,如下所示:
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M1 0 L1 75"/>
</svg>
当你这样做时会发生什么?
关于javascript - 基本垂直 SVG 线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38824659/