load image to a cube three.js

2019-01-29 02:24发布

问题:

Hi I trying to load a image to a cube but i don't know what is wrong. The cube is fine but not the image. Here is the link: http://diegoddox.bitbucket.org/loadimage/

var scene, camera, renderer;
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColorHex(0xeeeeee);
renderer.clear();
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 5000 );
camera.position.z = 800;
camera.lookAt(scene.position);
scene.add(camera);
var material = new THREE.MeshBasicMaterial({
    map: THREE.ImageUtils.loadTexture("img.jpg")
});
material.map.needsUpdate = true; 
var cube = new THREE.Mesh(new THREE.CubeGeometry(300, 300, 300), material);
cube.overdraw = true;
cube.position.x = 0;
cube.rotation.x = -20;
cube.rotation.z = -2;
scene.add(cube);
renderer.render(scene, camera);

回答1:

The image loading is asynchronous.

What is happening is that your single render() call is occurring before the image finishes loading.

Enter

renderer.render(scene, camera);

into the Console, and you will see that the texture renders.

You need to add a callback to your loadTexture() function and call render() from there, or, alternatively, you can add an animation loop using requestAnimationFrame().