【问题标题】:How to change SVG animation duration without changing element's position on path?如何在不更改元素在路径上的位置的情况下更改 SVG 动画持续时间?
【发布时间】:2020-07-24 06:18:54
【问题描述】:

我正在尝试在 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)。

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

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

【问题讨论】:

  • 你可以反复调用 setCurrentTime 来调整。
  • @RobertLongson 我已经尝试过了,但 setCurrentTime 适用于当前持续时间。当我更改路径持续时间时, setCurrentTime 无济于事,因为我失去了以前的位置。或者你是什么意思?
  • @RobertLongson 请在此处查看 (stackblitz.com/edit/js-bags2w) 现在是纯 JS 和 SVG

标签: angular svg svg-animate


【解决方案1】:

如果我们在 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>

【讨论】:

  • 非常感谢!当你看到它时,它是如此简单和合乎逻辑......
猜你喜欢
  • 1970-01-01
  • 2018-06-20
  • 2020-09-13
  • 2013-11-19
  • 2011-05-05
  • 2018-07-24
  • 2015-02-01
  • 2013-01-18
相关资源
最近更新 更多