问题
Am creating a guitar string like path SVG and I'm trying to integrate courses on the said path. So its kinda like a road path thing where there are few stages or modules in it.
What I wanted to achieve is to add a linear animation on the path whenever the current step is active. By linear animation I mean its kinda like a draw on svg but the only difference is that it fills the path itself. I can't find any resources how to do it and mostly the results are more on the Draw animation.
Currently I used transition:.5s all ease;
to have simple animation but I want the linear animation to make it cooler.
Here's my pen for the svg https://codepen.io/leonardpbdigital/pen/eYpvNVL I added a simple script just for this demo.
回答1:
As Paulie_D said in the comments, the key is animating the SVG stroke-dash-offset
. Here's a little more detail about how that works.
Basically, it's creating a dashed stroke on the line (use an open path to make this work the best) where each "dash" is 100% the length of the line and each space between dashes is the same size. Then it moves the first "dash" from off the end of the path to fill the path up.
The key here is that the path definition in the CSS must include pathlength
set to 1 (same as 100%).
Now you can animate the stroke properties in CSS. This includes stroke-width
, stroke
(color), stroke-width
, etc.
.container {
margin: 30px;
}
#path {
stroke: #dadada;
stroke-dasharray: 1;
stroke-dashoffset: 0;
fill: none;
stroke-width: 10;
stroke-linecap: round;
stroke-linejoin: round;
animation: reveal 3s linear infinite;
}
@keyframes reveal {
from {
stroke: #111111;
stroke-dashoffset: 1;
}
to {
stroke-dashoffset: 0;
stroke: skyblue;
}
}
<div class="container">
<svg width="553px" height="239px" viewBox="0 0 553 239" x="0px" y="0px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g fill-rule="evenodd">
<path id="path"
pathLength="1"
d="M10,11 L114.530616,11 C122.360858,11 126.275979,15.9504251 126.27598,25.8512759 C126.27598,35.7521268 126.27598,98.9884467 126.27598,215.560235 C126.27598,223.186745 129.049387,227 134.596203,227 C140.143019,227 190.952571,227 287.02486,227 C295.080229,227 299.107914,223.186745 299.107914,215.560235 C299.107914,207.933725 299.107914,190.752337 299.107914,164.016069 C299.461684,117.430837 317.3583,94.1382206 352.797762,94.1382206 C388.237223,94.1382206 439.637969,94.1382206 507,94.1382206"></path>
</g>
</svg>
</div>
But, simply using the stroked path alone means you don't have as much control. If you make the path an SVG mask there's so much more opportunity. For example, you can use a gradient background to color "sections" of the line. You can even reveal a picture. Here's an example of how you can use different colors and step to each section.
来源:https://stackoverflow.com/questions/61400356/how-to-make-linear-css-transition-to-svg-path