gpt4 book ai didi

angular - requestAnimationFrame 只被调用一次

转载 作者:太空狗 更新时间:2023-10-29 17:08:41 27 4
gpt4 key购买 nike

我正在尝试在我的 Ionic 2 应用程序中使用 ThreeJS 实现非常基本的动画。基本上试图旋转一个立方体。但是立方体并没有旋转,因为 requestAnimationFrame 只在渲染循环中执行一次。

我只能看到这个。 enter image description here

没有旋转动画。我在下面分享我的代码。

home.html

<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content>
<div #webgloutput></div>
</ion-content>

home.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';

import * as THREE from 'three';


@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('webgloutput') webgloutput: ElementRef;


private renderer: any;
private scene: any;
private camera: any;
private cube: any;

constructor(public navCtrl: NavController) {
}

ngOnInit() {
this.initThree();
}

initThree() {
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize( window.innerWidth, window.innerHeight );
this.webgloutput.nativeElement.appendChild(this.renderer.domElement);

let geometry = new THREE.BoxGeometry(1, 1, 1);

let material = new THREE.MeshBasicMaterial({ color: 0x00ff00});
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
this.camera.position.z = 5;

this.render();
}


render() {
console.log("render called");
requestAnimationFrame(() => this.render);

this.cube.rotation.x += 0.5;
this.cube.rotation.y += 0.5;
this.renderer.render(this.scene, this.camera);
}

}

最佳答案

问题是您没有正确调用 requestAnimationFrame。您没有直接将渲染函数传递给它,而是一个 返回 渲染函数的 lambda 函数。

将行 requestAnimationFrame(() => this.render); 更改为 requestAnimationFrame(this.render);

编辑:

当像您一样使用 ES2015 类时,请务必记住类方法是声明为对象属性的函数。上下文 (this) 将是方法附加到的对象。因此,当将方法传递给 requestAnimationFrame(...) 方法时,将不再使用相同的对象引用来调用它。因此,我们需要在将渲染方法传递给 requestAnimationFrame(...) 之前绑定(bind)它的上下文:

requestAnimationFrame(this.render.bind(this));

这在 this blog post 中得到了很好的解释。 . (不要介意它专注于 React,原理和示例是特定于 ES2015 的)。

关于angular - requestAnimationFrame 只被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com