joh*_*214 3 html javascript css jquery svg
我想知道如何使用 javascript 而不是 HTML 来制作 SVG 路径的动画。目前,我发现了几篇关于使用 javascript 制作动画的溢出文章,并且在 jQuery 中发现了许多更改 javascript 属性的文章。
我找到的链接: 用动画填充颜色 SVG 路径 通过 javascript 对 SVG 路径进行动画处理
有谁知道我如何将这些技术应用到下面的路径,因为它与 HTML 配合得很好,但我想控制动画的持续时间。
<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>
Run Code Online (Sandbox Code Playgroud)
问题是 javascript 无法正常工作
$(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( "from", 1);
},
complete: function () {
$("#myPath").attr("fill", "url(#left-to-right)");
}
}
);
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
我现在必须如何更改 javascript、fx 和属性,才能使动画像当前 HTML 一样工作?
如果您想使用 javascript 为渐变添加动画效果,则不再需要该<animate>
元素。
//all the stops
let ss = document.querySelectorAll("#left-to-right stop");
let start = null;
let progress = 0;//the progress of the animation
let duration = 2000; //2 seconds in millisecinds
let rid = null;//request animation id
function Frame(timestamp) {
rid = window.requestAnimationFrame(Frame);
if (!start) start = timestamp;
progress = timestamp - start;
if (progress <= duration) {
//for each stop reset the offset attribute
ss.forEach(s => {
s.setAttributeNS(null, "offset", progress / duration);
});
}
// if the animation is over cancel the animation
if (progress >= duration){window.cancelAnimationFrame(rid)}
}
Frame();
Run Code Online (Sandbox Code Playgroud)
<svg width="300" height="300">
<defs>
<linearGradient id="left-to-right">
<stop offset="0" stop-color="#ff0000"></stop>
<stop offset="0" stop-color="#fff" ></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>
Run Code Online (Sandbox Code Playgroud)
我希望你会发现这很有用。