我在我的项目中使用 bodymovin 脚本。即使我的一些动画 SVG 在浏览器中呈现,我仍然收到此错误
Uncaught TypeError: Cannot read property 'appendChild' of undefined
at SVGRenderer.configAnimation (bodymovin.min.js:5)
at AnimationItem.configAnimation (bodymovin.min.js:9)
at XMLHttpRequest.r.onreadystatechange (bodymovin.min.js:9)
at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (zone.js:1075)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
at invokeTask (zone.js:1370)
at XMLHttpRequest.globalZoneAwareCallback (zone.js:1388)
根据这个答案,我想我应该在页面上的所有内容加载后运行 bodymovin 脚本。我已经更新了代码,考虑到了新的建议
索引.html
<!doctype html>
<html lang="en">
<head>...</head>
<body>...
<div class="full-app-body">
<app-root></app-root>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/4.10.2/bodymovin.min.js"></script>
</body>
</html>
app.component.ts
import { Component, ElementRef, OnInit, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute, RouterOutlet, Routes } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgClass, CommonModule } from '@angular/common';
...
export class AppComponent implements AfterViewInit {
constructor(public router: Router, private elementRef: ElementRef) {}
...
ngAfterViewInit() {
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = '/assets/js/animations.js';
// this.elementRef.nativeElement.appendChild(s);
document.body.appendChild(s);
}
app.component.html
<div id='bm'></div>
动画.js
var animation = bodymovin.loadAnimation({
container: document.getElementById('bm'),
renderer: 'svg',
loop: true,
autoplay: true,
path: './assets/images/ani/fatigue-data.json'
});