som*_*hbm 10 three.js requestanimationframe ionic2 angular
我正试图在我的Ionic 2应用程序中使用ThreeJS实现一个非常基本的动画.基本上是试图旋转立方体.但是多维数据集不会旋转,因为requestAnimationFrame只在render循环中执行一次.
没有旋转动画.我在下面分享我的代码.
home.html的
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div #webgloutput></div>
</ion-content>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
mic*_*nil 26
问题是您没有正确调用requestAnimationFrame.您没有直接传递渲染函数,而是返回一个返回渲染函数的lambda 函数.
将行更改requestAnimationFrame(() => this.render);为requestAnimationFrame(this.render);
编辑:
当像您一样使用ES2015类时,重要的是要记住类方法是声明为对象属性的函数.上下文(this)将是该方法所附加的对象.因此,当将方法传递给requestAnimationFrame(...)方法时,将不再使用相同的对象引用调用它.因此,我们需要绑定render方法的上下文,然后再将其传递给requestAnimationFrame(...):
requestAnimationFrame(this.render.bind(this));
Run Code Online (Sandbox Code Playgroud)
这篇博文很好地阐述了这一点.(不介意它专注于React,原则和示例是ES2015特定的).
| 归档时间: |
|
| 查看次数: |
4778 次 |
| 最近记录: |