【发布时间】:2018-01-19 09:16:37
【问题描述】:
我正在尝试在我的 Ionic 2 应用程序中使用 HTML5 画布制作动画。为此,我必须使用window.requestAnimationFrame() 为我的画布设置动画。这是我的代码:
import { Component, ViewChild, Renderer } from '@angular/core';
import { Platform } from 'ionic-angular';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
...
export class CubePage {
@ViewChild('glCanvas') canvas: any;
canvasElement: any;
ctx: any;
radius: number;
leftBallX: number;
leftBallY: number;
rightBallX: number;
rightBallY: number;
constructor(public navCtrl: NavController, public navParams: NavParams, public renderer: Renderer, public platform: Platform) {
}
ngAfterViewInit() {
console.log(this.canvas);
this.radius = 25;
this.canvasElement = this.canvas.nativeElement;
this.renderer.setElementAttribute(this.canvasElement, 'width', this.platform.width() + "");
this.renderer.setElementAttribute(this.canvasElement, 'height', this.platform.height() + "");
this.ctx = this.canvasElement.getContext('2d');
this.leftBallX = 5;
this.leftBallY = 5;
window.requestAnimationFrame(this.cycle);
}
cycle() {
if (this.leftBallX < this.platform.width() / 2) {
this.ctx.clearRect(0, 0, this.platform.width(), this.platform.height());
this.drawCenterLine();
this.updateLeftBall(this.leftBallX + 5, this.leftBallY);
this.drawLeftBall();
}
window.requestAnimationFrame(this.cycle);
}
...
}
当我在网络浏览器中加载应用程序时,它会给出运行时错误Cannot read property 'leftBallX' of undefined。但是,当我消除 window.requestAnimationFrame(this.cycle) 行,用 this.cycle() 替换第一行时,没有错误。在 Ionic/Angular 中使用 window 有问题吗?
【问题讨论】:
-
试试
requestAnimationFrame(()=>{this.cycle()}) -
我发布了一个答案来解释。请看
标签: html angular typescript ionic2 html5-canvas