2017-04-18 117 views
2

我想在我的Ionic 2應用程序中使用ThreeJS實現一個非常基本的動畫。基本上試圖旋轉一個立方體。但多維數據集不旋轉,因爲requestAnimationFrame在渲染循環中只執行一次。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); 
    } 

} 
+0

試試這個...當你調用this.render();把它放在setInterval(function(){that.render},50)中? – getbuckts

回答

4

的問題是,你是不是正確的呼喚你的requestAnimationFrame。您沒有直接通過渲染函數,而是使用渲染函數返回的lambda函數。

改線requestAnimationFrame(() => this.render);requestAnimationFrame(this.render);

編輯:

當使用ES2015類,如你,一定要記住類的方法聲明爲對象屬性的功能是非常重要的。上下文(this)將是該方法所附帶的對象。因此,將該方法傳遞給requestAnimationFrame(...)方法時,將不再使用相同的對象引用調用該方法。正因爲如此,我們需要把它傳遞給requestAnimationFrame(...)之前渲染方法的上下文綁定:

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

this blog post是expained很好。 (不要介意它專注於React,原則和示例是ES2015的具體內容)。

+0

是的,我已經試過這個在第一個地方。但是這樣做編譯器會拋出這個錯誤** TypeError:無法讀取undefined **的屬性'render'。 它無法識別渲染是方法。可能在這裏以某種方式**這個**上下文被搞砸了。 – somnathbm

+1

@somnathbm做'''requestAnimationFrame(this.render.bind(this));'''工作嗎? – micnil

+0

ahh yeah終於。它確實有效。謝謝@micnil – somnathbm