【问题标题】:window.requestAnimationFrame() not working in Ionic2 applicationwindow.requestAnimationFrame() 在 Ionic2 应用程序中不起作用
【发布时间】: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(()=&gt;{this.cycle()})
  • 我发布了一个答案来解释。请看

标签: html angular typescript ionic2 html5-canvas


【解决方案1】:

要解决您的问题,首先,您需要了解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对象,所以你在this中找不到foo属性。
当您通过方式#2(箭头函数)调用函数时,javascript 不会重新绑定this 对象,因此您可以按预期使用this

现在您可以使用箭头功能解决您的问题:

requestAnimationFrame(()=>{this.cycle()})

查看更多关于arrow function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2021-04-30
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多