我正在尝试在我的 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
当我在 Web 浏览器中加载应用程序时,它会出现运行时错误。但是,当我消除这些window.requestAnimationFrame(this.cycle)
行,用 替换第一个时this.cycle()
,没有错误。window
在 Ionic/Angular 中使用有问题吗?
要解决您的问题,首先,您需要了解this
调用 javascript 函数时的上下文。让我们看看例子:
foo = 0;
ngAfterViewInit(){
let self = this;
//way #1
setTimeout(function(){
console.log(this.foo); //undefinded; because this != self;
},1000);
//way #2
setTimeout(()=>{
console.log(this.foo); //0; because this == self;
},1000)
}
当您通过#1 方式调用函数时,javascript 会重新绑定this
对象,因此您无法foo
在this
.
当您通过#2(箭头函数)调用函数时,javascript 不会重新绑定this
对象,因此您可以this
按预期使用。
现在您可以使用箭头函数解决您的问题:
requestAnimationFrame(()=>{this.cycle()})
查看更多关于箭头函数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句