简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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