【问题标题】:three.js does not render, must have requestAnimationFrame?三.js不渲染,一定有requestAnimationFrame?
【发布时间】:2013-09-30 04:59:42
【问题描述】:

我正在做第 2 章 - WebGL 启动和运行一书中的示例。

我想展示一个静态贴图立方体。

此代码不起作用:

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);

}

但是在我添加一个run 函数并调用requestAnimationFrame 后,它显示了立方体

...
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);

}

谁能解释一下为什么? 谢谢!

【问题讨论】:

    标签: javascript three.js rendering


    【解决方案1】:

    纹理(贴图)是异步加载的,所以在第一个示例中,当您调用render() 时,纹理尚不可用。你需要有一个纹理加载回调来在图像加载时重新渲染,或者像你对 requestAnimationFrame 所做的那样,有一个连续的渲染循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-17
      • 2012-08-10
      • 2013-02-18
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多