2013-09-30 3 views
0

Je suis en train de faire l'exemple du chapitre 2 - Web Up et Running Book.trois.js ne rend pas, doit avoir requestAnimationFrame?

Je souhaite afficher un cube mappé en texture statique.

Ce code ne fonctionne pas:

var camera = null, 
renderer = null, 
scene = null, 
cube = null, 
animating = false; 

function onLoad() { 
// Grab our container div 
var container = document.getElementById("container"); 
// Create the Three.js renderer, add it to our div 
renderer = new THREE.WebGLRenderer({ 
    antialias: true 
}); 
renderer.setSize(container.offsetWidth, container.offsetHeight); 
container.appendChild(renderer.domElement); 
// Create a new Three.js scene 
scene = new THREE.Scene(); 
// Put in a camera 
camera = new THREE.PerspectiveCamera(45, 
    container.offsetWidth/container.offsetHeight, 1, 4000); 
camera.position.set(0, 0, 3); 
// Create a directional light to show off the object 
var light = new THREE.DirectionalLight(0xffffff, 1.5); 
light.position.set(0, 0, 1); 
scene.add(light); 
// Create a shaded, texture-mapped cube and add it to the scene 
// First, create the texture map 
var mapUrl = "cuttherope.jpg"; 
var map = THREE.ImageUtils.loadTexture(mapUrl); 
// Now, create a Phong material to show shading; pass in the map 
var material = new THREE.MeshPhongMaterial({ 
    map: map 
}); 
// Create the cube geometry 
var geometry = new THREE.CubeGeometry(1, 1, 1); 
// And put the geometry and material together into a mesh 
cube = new THREE.Mesh(geometry, material); 
// Turn it toward the scene, or we won't see the cube shape! 
cube.rotation.x = Math.PI/5; 
cube.rotation.y = Math.PI/5; 
// Add the cube to our scene 
scene.add(cube); 
renderer.render(scene, camera); 

}

Mais après que j'ajoute une fonction run et appelle requestAnimationFrame, il apparaît le cube

... 
cube.rotation.x = Math.PI/5; 
cube.rotation.y = Math.PI/5; 
// Add the cube to our scene 
scene.add(cube); 
run(); 
} 

function run() { 
renderer.render(scene, camera); 
requestAnimationFrame(run); 

}

Quelqu'un peut-il m'expliquer pourquoi? Merci!

Répondre

3

La texture (carte) se charge de manière asynchrone, donc dans le premier exemple, lorsque vous appelez render(), la texture n'est pas encore disponible. Vous devez avoir un callback de chargement de texture à ré-afficher quand l'image est chargée, ou comme vous l'avez fait avec requestAnimationFrame, avoir une boucle de rendu continue.