即使在 运行 文件通过本地服务器后也没有加载纹理

Texture not loading even after running file through local server

纹理加载为黑色。我尝试通过本地服务器 (Servez) 运行 the.html 文件,但这似乎不是问题所在。我正在使用 visual studio 代码。代码似乎工作正常,控制台没有显示任何错误。

这是我的代码:

window.onload = function() {

    //Define the WebGL renderer:

    var renderer = new THREE.WebGLRenderer(); //specify the we will use WebGL
    renderer.setSize( 800, 600 ); //scene size (Width, Height)
    document.body.appendChild( renderer.domElement );


    //Initialize (create) the scene:

    var scene = new THREE.Scene();


    //Define the camera:

    var camera = new THREE.PerspectiveCamera(
        35,             // Field of view
        800 / 600,      // Aspect ratio
        0.1,            // Near plane
        10000           // Far plane
    );
    camera.position.x= 0;  //default value anyway
    camera.position.y= 0;  //default value anyway
    camera.position.z = 300;
    camera.lookAt( scene.position );


    //Define the objects for the scene:

   var skygeo = new THREE.SphereGeometry(150, 40, 20);
   var skytexture = new THREE.TextureLoader().load("sky.jpg");
   var skymat = new THREE.MeshBasicMaterial({map:skytexture});
   skymat.side = THREE.Backside;
   var skydome = new THREE.Mesh(skygeo, skymat);
   scene.add(skydome);

    // create a point light:
    var pointLight = new THREE.PointLight(0xFFFFFF);
    // set the light position:
    pointLight.position.x = 10;
    pointLight.position.y = 50;
    pointLight.position.z = 100;
    // add the light to the scene:
    scene.add(pointLight);

    // it renders the scene:
    renderer.render( scene, camera );

};

我发现这里(https://discourse.threejs.org/t/texture-loading-not-working-on-server/14910/10)可能是因为图像文件损坏了。我还在其他地方发现这可能是因为像 AdBlock 这样的浏览器扩展,但是删除扩展并没有解决它。

这是什么原因?

您只调用了一次 renderer.render( scene, camera );,在初始化纹理加载器之后立即调用。纹理加载是异步的,需要一些时间,因此您在加载纹理之前渲染场景。您需要在 纹理加载完成后调用 render 。为此,您可以使用 the onLoad callback, or you could see the basic docs on creating a scene 作为有关如何连续渲染的示例:

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