在 THREE.js 中使用纹理 [英] Using textures in THREE.js

查看:36
本文介绍了在 THREE.js 中使用纹理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 THREE.js 开始,我试图绘制一个带有纹理的矩形,由单一光源照亮.我认为这很简单(为简洁起见省略了 HTML):

I am starting with THREE.js, and I am trying to draw a rectangle with a texture on it, lit by a single source of light. I think this is as simple as it gets (HTML omitted for brevity):

function loadScene() {
    var world = document.getElementById('world'),
        WIDTH = 1200,
        HEIGHT = 500,
        VIEW_ANGLE = 45,
        ASPECT = WIDTH / HEIGHT,
        NEAR = 0.1,
        FAR = 10000,

        renderer = new THREE.WebGLRenderer(),
        camera = new THREE.Camera(VIEW_ANGLE, ASPECT, NEAR, FAR),
        scene = new THREE.Scene(),
        texture = THREE.ImageUtils.loadTexture('crate.gif'),
        material = new THREE.MeshBasicMaterial({map: texture}),
        // material = new THREE.MeshPhongMaterial({color: 0xCC0000});
        geometry = new THREE.PlaneGeometry(100, 100),
        mesh = new THREE.Mesh(geometry, material),
        pointLight = new THREE.PointLight(0xFFFFFF);

    camera.position.z = 200;    
    renderer.setSize(WIDTH, HEIGHT);
    scene.addChild(mesh);
    world.appendChild(renderer.domElement);
    pointLight.position.x = 50;
    pointLight.position.y = 50;
    pointLight.position.z = 130;
    scene.addLight(pointLight); 
    renderer.render(scene, camera);
}

问题是,我什么都看不到.如果我更改材料并使用注释的材料,则会如我所愿地出现一个正方形.请注意

The problem is, I cannot see anything. If I change the material and use the commented one, a square appears as I would expect. Note that

  • 纹理是 256x256,所以它的边是 2 的幂
  • 这个函数实际上是在body加载的时候调用的;它确实适用于不同的材料.
  • 即使我从网络服务器提供文件,它也不起作用,所以这不是跨域策略不允许加载图像的问题.

我做错了什么?

推荐答案

加载图像时,渲染器已经绘制了场景,因此为时已晚.解决办法是改

By the time the image is loaded, the renderer has already drawn the scene, hence it is too late. The solution is to change

texture = THREE.ImageUtils.loadTexture('crate.gif'),

进入

texture = THREE.ImageUtils.loadTexture('crate.gif', {}, function() {
    renderer.render(scene);
}),

这篇关于在 THREE.js 中使用纹理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆