根据您的 SVG 的复杂程度,您可能会发现如果没有大量优化,足够快地替换 DOM 对象将是一个挑战(this answer 包含很多有用的细节和比较)
如何实现这一点的一个非常简单的 Javascript 示例是逐步遍历 SVG 项目数组并在与您的帧速率对齐的 setInterval 计时器上将它们换出(我使用了基于此的代码进行后台加载AndroidTV 应用程序上的动画,它运行得非常可靠)
<svg height="200" width="200" id="svg">
</svg>
<script>
var fps = 30
var f = 0
var svgA = [
'<circle cx="50" cy="60" r="40" stroke="black"stroke-width="3" fill="red" />',
'<circle cx="55" cy="62" r="42" stroke="black"stroke-width="4" fill="red" />',
'<circle cx="60" cy="64" r="44" stroke="black"stroke-width="5" fill="red" />',
'<circle cx="65" cy="66" r="46" stroke="black"stroke-width="6" fill="red" />',
'<circle cx="70" cy="68" r="48" stroke="black"stroke-width="7" fill="red" />',
'<circle cx="74" cy="70" r="50" stroke="black"stroke-width="8" fill="red" />',
'<circle cx="77" cy="72" r="48" stroke="black"stroke-width="9" fill="red" />',
'<circle cx="79" cy="74" r="46" stroke="black"stroke-width="8" fill="red" />',
'<circle cx="80" cy="76" r="44" stroke="black"stroke-width="7" fill="red" />',
'<circle cx="79" cy="74" r="46" stroke="black"stroke-width="6" fill="red" />',
'<circle cx="77" cy="72" r="48" stroke="black"stroke-width="5" fill="red" />',
'<circle cx="74" cy="70" r="46" stroke="black"stroke-width="4" fill="red" />',
'<circle cx="70" cy="68" r="44" stroke="black"stroke-width="3" fill="red" />',
'<circle cx="65" cy="64" r="42" stroke="black"stroke-width="2" fill="red" />',
'<circle cx="55" cy="62" r="40" stroke="black"stroke-width="3" fill="red" />'
]
var i = setInterval(function() {nextFrame();}, 1000 / fps);
function nextFrame() {
document.getElementById("svg").innerHTML = svgA[f];
f=(f+1)%svgA.length
if (f==0) {
clearInterval(i)
}
}
</script>