I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes.
Some helpful links I found: Fill color SVG path with animation Animate SVG path via JavaScript
Is there anyone who knows how to apply these techniques to the following path? Although it currently works fine in HTML, I would like to be able to control the duration of the animation.
<svg width="300" height="300">
<defs>
<linearGradient id="left-to-right">
<stop offset="0" stop-color="#ff0000">
<animate dur="2s" attributeName="offset" opacity= 0.1 fill="freeze" from="0" to="1" />
</stop>
<stop offset="0" stop-color="#fff" stop-opacity="0.1">
<animate dur="2s" attributeName="offset" opacity="0.1" fill="freeze" from="0" to="1" />
</stop>
</linearGradient>
</defs>
<path id="myPath"
d="M 280 210 Q 237 144 180 140 Q 120 144 80 210 L 280 210 "
stroke="black" fill="url(#left-to-right)" />
</svg>
The issue is that the JavaScript code is not functioning as expected.
$(function(){
$(this).animate(
{
textIndent: 1,
}, {
duration: 3000,
step: function ( now, fx ) {
var from = 0,
to = 700,
r = from + to * ( now - fx.start ) / ( fx.end - fx.start );
$("#left-to-right").attr( "from", 0);
$("#left-to-right").attr( "to", 1);
},
complete: function () {
$("#myPath").attr("fill", "url(#left-to-right)");
}
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg width="300" height="300">
<defs>
<linearGradient id="left-to-right">
<stop offset="0" stop-color="#ff0000">
<animate dur="2s" attributeName="offset" opacity= 0.1 fill="freeze" from="0" to="1" />
</stop>
</linearGradient>
</defs>
<path id="myPath"
d="M 280 210 Q 237 144 180 140 Q 120 144 80 210 L 280 210 "
stroke="black" fill="url(#left-to-right)" />
</svg>
What changes do I need to make to the JavaScript code, particularly in relation to the 'now', 'fx' values, and attributes, in order for the animation to work correctly as it does in the current HTML version?