简体   繁体   English

three.js纹理不适用于网格

[英]three.js texture not applied to mesh

I am trying to apply texture to my sphere mesh with the following. 我正在尝试通过以下方法将纹理应用于球体网格。

var loader =  new THREE.TextureLoader();
var balltex = loader.load("pic1.jpg");
var ballmat = new THREE.MeshBasicMaterial({ map:balltex }); 
var ballgeo = new THREE.SphereGeometry( 0.3, 20, 20 );
var ball = new THREE.Mesh( ballgeo , ballmat );
scene.add(ball);    

Now I am just getting a black sphere instead of textured sphere. 现在,我得到的是黑色球体,而不是纹理球体。 I do not know what is the problem in the code. 我不知道代码中的问题是什么。
Please help me. 请帮我。

It's hard to say for sure without a complete example, but my first guess is the simplest case: the texture isn't finished loading by the time the mesh is rendered. 没有完整的示例很难确定,但是我的第一个猜测是最简单的情况:在渲染网格时,纹理还没有完成加载。

If that's the problem, make sure the texture(s) are loaded before you call your render loop. 如果这是问题所在,请确保在调用渲染循环之前已加载纹理。 There are many ways to do this and it's hard to say which is best without seeing your code, but the most straightforward way to handle it is pass a function to the loader's load() method and call your renderer from it. 有很多方法可以做到这一点,很难看到最好的代码而不看代码,但是处理它的最直接方法是将函数传递给加载器的load()方法,并从中调用渲染器。 A simple but complete example reworking the code you posted: 一个简单但完整的示例重新编写您发布的代码:

var scene, camera, light, renderer, balltex;

load();

function load() {
        var loader;

        loader = new THREE.TextureLoader(new THREE.LoadingManager());
        loader.load('pic1.jpg', function(obj) {
                balltex = obj;
                init();
                animate();
        });
}

function init() {
        var height = 500, width = 500, bg = '#000000';

        scene = new THREE.Scene();

        camera = new THREE.PerspectiveCamera(45, height/width, 1, 10000);
        camera.position.set(1.5, 1.5, 1.5);
        camera.lookAt(new THREE.Vector3(0, 0, 0));
        scene.add(camera);

        light = new THREE.AmbientLight(0xffffff);
        scene.add(light);

        var ballmat = new THREE.MeshBasicMaterial({
                map:    balltex
        }); 
        var ballgeo = new THREE.SphereGeometry( 0.3, 20, 20 );
        var ball = new THREE.Mesh( ballgeo , ballmat );
        scene.add(ball);

        renderer = new THREE.WebGLRenderer({ antialias: true } );
        renderer.setClearColor(bg);
        renderer.setSize(width, height);

        var d = document.createElement('div');
        document.body.appendChild(d);
        d.appendChild(renderer.domElement);

        var c = document.getElementsByTagName('canvas')[0];
        c.style.width = width + 'px';
        c.style.height = height + 'px'
}

function animate() {
        requestAnimationFrame(animate);
        render();
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM