javascript - Three.js不渲染,一定要有requestAnimationFrame吗?

标签 javascript three.js rendering

我正在做第 2 章 - WebGL Up and Running 书中的示例。

我想显示一个静态纹理映射的立方体。

此代码不起作用:

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

}

有人可以解释一下为什么吗? 谢谢!

最佳答案

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

关于javascript - Three.js不渲染,一定要有requestAnimationFrame吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086690/

相关文章:

javascript - datepicker 更改月份未在 Chrome 中打开

reactjs - React 三纤 - Tween Camera

asp.net - ASP.Net 从哪里获取其呈现的 ID?

c++ - 如何将网页绘制到内存DC中?

javascript - Three.js - 网格表面的极端阴影

Java 应用程序 - AWT 渲染导致抗锯齿打开时文本损坏

javascript - 如何通过单击按钮使用 jquery 检查 html 表中带有复选框 id 的复选框

javascript - 使用 JQuery.MSDropDown 更新 selectedIndex 选项菜单

javascript - 捕获 HTML 页面中的新请求

javascript - @ react 三/ react 三纤维 : useLoader() to load new file on props change