How to do line animation using CSS and SVG
Tags: javascript,css,svg
Problem :
My goal is to create scrolling lines similar to this site. I have started using a simple SVG shape to try and get it to work. I can do a simple animation, but not sure how to fill a specific color from start to finish.
My SVG:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="75px" height="100px" viewBox="0 -450 1230 1640" preserveAspectRatio="xMidYMid meet">
<path class="path" d="M131.2,-318.8a672.4,672.4,0,0,1,0,1344.8" stroke="black" id="e7_circleArc" style="fill: none; stroke-width: 3px; vector-effect: non-scaling-stroke; stroke-dasharray: 5px, 5px;" />
My CSS
.path {
stroke-dasharray: 500;
stroke-dashoffset: 5000;
animation: dash 2s linear forwards;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
You can see the working fiddle here - https://jsfiddle.net/cbd9L2L3/
Solution :
I used the same method as the link you posted - animating the 'bottom' value of clip: rect()
with jquery. With the difference that I went and used SVG shapes (one for the background and one for the one to be animated) Just a note that clip
is apparently deprecated and has been replaced with clip-path
. I tried with clip-path
but couldn't achieve the same result.
Absolutely position both lines on top of one another if it's not obvious:
$('#line1-overlay').animate({
fontSize: 515 //some unimportant CSS to animate so we get some values - and height of the line
}, {
duration: 2000,
step: function (now, fx) { //now is the animated value from initial css value
$(this).css('clip', 'rect(0px, 217px, ' + now + 'px, 0px)')
}
});
.line-container {
position: relative;
}
.line {
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="line-container">
<svg version="1.1" class="line" id="line1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="217px" height="515px" viewBox="0 0 217 515" enable-background="new 0 0 217 515" xml:space="preserve">
<path fill="#FFFFFF" stroke="#CCCCCC" stroke-width="4" stroke-miterlimit="10" d="M77.229,10.222c64,22,142,140,129,203
c-13,63-152,60-186,118c-34,58,61,159,130,177"/>
</svg>
<svg version="1.1" class="line" id="line1-overlay" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="217px" height="515px" viewBox="0 0 217 515" enable-background="new 0 0 217 515" xml:space="preserve">
<path fill="#FFFFFF" stroke="#000000" stroke-width="4" stroke-miterlimit="10" d="M77.229,10.222c64,22,142,140,129,203
c-13,63-152,60-186,118c-34,58,61,159,130,177"/>
</svg>
</div>
Also: JSFiddle DEMO
Thanks partly to this answer.