SVGSVGElement的规范包含类似pauseAnimations()
或unpauseAnimations()
的方法。但是如何在Angular 9中访问这些方法?或者如何暂停/恢复SVG路径动画?
<svg id="rootSVG" width="500" viewBox="50 0 700 400" xmlns="http://www.w3.org/2000/svg">
<svg:circle r="10" fill="white" id="white">
<svg:animateMotion
id="innerTrack"
[attr.dur]="durationInner"
begin="indefinite"
repeatCount="0"
calcMode="linear"
[attr.path]="innerPath"
(begin)="status()"
/>
</svg:circle>
</svg>
在纯JS中,我会做类似的事情:
var pause = document.getElementById('innerTrack');
pause.pauseAnimations();
但是当我使用Angular 9时,出现编译错误:
error TS2551: Property 'pauseAnimations' does not exist on type 'HTMLElement'. Did you mean 'getAnimations'?
所以问题是:怎么办?
因此,您需要在#rootSVG:SVGSVGElement上访问方法。
要在Angular中这样做,您可以利用ViewChild并访问nativeElement及其方法:
<svg #rootSVG viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
<svg:path fill="none" stroke="lightgrey"
d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
<svg:circle r="5" fill="red">
<svg:animateMotion dur="3s" repeatCount="indefinite"
path="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
</svg:circle>
</svg>
现在在您的ts文件中,您需要在ngAfterViewInit挂钩中获取ViewChild,然后您可以开始调用有问题的方法:
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('rootSVG') animateMotion;
name = 'Angular';
ngAfterViewInit() {
setInterval(()=>{
this.animateMotion.nativeElement.pauseAnimations();
}, 500)
setInterval(()=>{
this.animateMotion.nativeElement.unpauseAnimations();
}, 1500)
}
}