首页 > 解决方案 > 如何在不更改元素在路径上的位置的情况下更改 SVG 动画持续时间?

问题描述

我正在尝试在 Angular 9 中实现赛道模拟。在非常简化的示例中,溜冰者从估计的完成时间开始,例如 10 秒。

<svg:circle r="10" fill="red" stroke-width="2" stroke="#00a2c1">
    <svg:animateMotion
        [attr.dur]="duration" 
        begin="0s"
        path="M 450 440 L 740 440 A 50 50 0 1 0 740 100 L 450 100 L 200 100 A 50 50 0 1 0 200 440 L 450 440"
        repeatCount="2" 
        calcMode="linear"
        fill="freeze"
    />
</svg:circle>

初始持续时间设置为该值。但现在是第一次测量。根据测量值重新推断完成时间,例如现在为 20 秒。

public duration:string = '10s';

ngOnInit() {
    setTimeout(() => {
        this.duration = '20s';
        this.changeDetectorRef.detectChanges(); 
    }, 2000);
}

现在出现了问题:当更改当前路径动画的持续时间时,会重新计算整个路径并且点会在路径上跳回(参见https://stackblitz.com/edit/angular-jbknyt)。

如何在不从当前位置移动圆圈的情况下更新/修改路径持续时间?

我想要的行为是,当测量的时间比初始值慢时,点在轨道上“等待”。当测量的时间快于路径上的点快进时......有没有办法做到这一点?

标签: angularsvgsvg-animate

解决方案


如果我们在 2 秒后将持续时间加倍,那么在我们的新时间线中,我们需要 4 秒。

// Write Javascript code!
const anim = document.getElementById('anim');
const svg = document.getElementsByTagName('svg')[0];

setTimeout(() => {
  console.log("change")

  anim.setAttribute('dur','20s');
  svg.setCurrentTime(4);
  
}, 2000);
<svg  width="400" viewBox="-20 50 1000 460" xmlns="http://www.w3.org/2000/svg">

	<path fill="#defefe" stroke-width="2" stroke="#000" path="M 450 440 L 740 440 A 50 50 0 1 0 740 100 L 450 100 L 200 100 A 50 50 0 1 0 200 440 L 450 440" />

	<circle r="10" fill="red" stroke-width="2" stroke="#00a2c1">
		<animateMotion
      id="anim"
	    dur="10s" 
			path="M 450 440 L 740 440 A 50 50 0 1 0 740 100 L 450 100 L 200 100 A 50 50 0 1 0 200 440 L 450 440"
	    repeatCount="2" 
	    calcMode="linear"
			fill="freeze"
		/>
	</circle>
</svg>


推荐阅读