(SVG - stroke-dsaharray)当我开始动画时,我的路径分为两条路径

我正在尝试在滚动时为 SVG 设置动画,我已经使用数学创建了我自己的 SVG 路径,并且它显示的正是我需要的,但是当我尝试使用 CSS {{ 在路径上添加效果时问题开始了1}}

我的问题是:动画从两个点开始,一个从开始,另一个在 q 命令之后,只要我使用了两次移动命令,一个在开始,一个在 q 曲线命令之后。

我一直试图解决这个问题,但它完全改变了绘制的 SVG。

这里有一个片段来解释它是如何与我一起工作的,

stroke-dasharray
const shape = document.querySelector('#shape');
window.addEventListener('scroll',slide);
function slide() {
     let value = 2000 - scrollY*4; 
shape.style.strokeDashoffset=  value;
}
body {
    background:black;
    -webkit-user-select:none;
}
#svgdiv {
position:fixed;
margin:auto;
top:1rem;
width:95%;
}
#div1 {
height:30rem;
}
#shape {
  stroke-dashoffset:2000;
  stroke-dasharray: 2000;
}
#shapebg {
  stroke-dashoffset:2000;
  stroke-dasharray: 0;
}
#div2 {
height:19rem;
}

如你所见,它从两点开始,但我需要动画从头开始并直接结束,

有什么提示吗?

jidan88 回答:(SVG - stroke-dsaharray)当我开始动画时,我的路径分为两条路径

我对您的代码进行了一些更改;

  1. 我删除了中间的 move to 命令以获得连续路径:M 525 180 595 220 变为 L595 220。由于您在 M 之后没有任何命令字母,因此默认情况下接下来的所有内容都是 L 行

  2. 你的路径的总长度是 2223 而不是 2000。我已经改变了它。要知道路径的长度,您需要使用 getTotalLength() 方法。

  3. 你滚动不够。在您的代码中 let value = 2000 - scrollY*4;#div1 { height:30rem;} 因为在这种情况下 1rem = 16px,30rem = 16*30 = 480。由于您需要滚动 2223,因此您需要使用 let value = 2000 - scrollY*4.631; (2223/480 = 4.631)

观察:我已经四舍五入的数字,你可以使用未四舍五入的数字

const shape = document.querySelector('#shape');
window.addEventListener('scroll',slide);
function slide() {
     let value = 2223 - scrollY*4.631; 
shape.style.strokeDashoffset=  value;
}

//console.log(shape.getTotalLength())
body {
    background:black;
    -webkit-user-select:none;
}
#svgdiv {
position:fixed;
margin:auto;
top:1rem;
width:95%;
}
#div1 {
height:30rem;
}
#shape {
  stroke-dashoffset:2223;
  stroke-dasharray: 2223;
}

#div2 {
height:19rem;
}
<div id="div1"></div>
<div id="svgdiv">
<svg viewBox="0 0 1080 500">
  <path id="shape" d="M0,0L10,50L10,50L40,120L40,120L235,50L235,50Q685,30,525,180L 595 220 595 220 605 300 605 300 675 250 675 250 725 320 725 320 765 255 765 255 835 260 835 260 810 200 810 200 890 70 890 70 1050 130 1050 130 1040 260 1040 260 880 270 880 270 1079 300" stroke="purple" stroke-width="2.5" fill="none" />
 
  <path id="shapebg"  d="M0,180L 595 220 595 220 605 300 605 300 675 250 675 250 725 320 725 320 765 255 765 255 835 260 835 260 810 200 810 200 890 70 890 70 1050 130 1050 130 1040 260 1040 260 880 270 880 270 1079 300" stroke="purple" stroke-width="1.5" fill="none" />

</svg>
</div>

<div id="div2">
</div>

本文链接:https://www.f2er.com/888636.html

大家都在问