在 ThreeJS 中为 .obj 添加颜色 [英] Add color to .obj in ThreeJS

查看:91
本文介绍了在 ThreeJS 中为 .obj 添加颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 ThreeJS 的新手,有一个简单的问题.我有以下可以正常工作的代码,但我无法为我的 .obj 添加颜色.简而言之,我在 Solidworks 2012 中设计了一个游戏控制器,然后将 CAD 文件导出为 .stl.然后我使用 MeshLab 将 .stl 导出为 .obj.现在我在 ThreeJS 中使用 .obj 并且它可以工作,但是我一生都无法将颜色添加到 .obj 中.这是代码

<html lang="zh-cn"><头><title>three.js webgl - loaders - vtk loader</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"><风格>身体 {字体系列:等宽;背景色:#000;颜色:#fff;边距:0px;溢出:隐藏;}#信息{颜色:#fff;位置:绝对;顶部:10px;宽度:100%;文本对齐:居中;z-索引:100;显示:块;}#info a, .button { 颜色:#f00;字体粗细:粗体;文字装饰:下划线;光标:指针 }</风格><身体><div id="信息"><a href="" target="_blank">three.js</a>——vtk 格式加载器测试 -来自<a href="" target="_blank">GeorgiaTech Lagre Geometric Model Archive</a>的模型,

<script src="three.min.js"></script><script src="TrackballControls.js"></script><script src="OBJLoader.js"></script><script src="BinaryLoader.js"></script><script src="Detector.js"></script><script src="stats.min.js"></script><脚本>if (!Detector.webgl) Detector.addGetWebGLMessage();var 容器,统计数据;var 相机、控件、场景、渲染器;无功十字架;在里面();动画();函数初始化(){camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 0.01, 1e10 );相机.位置.z = 200;相机位置 y = 200;控件 = 新的 THREE.TrackballControls(camera);control.rotateSpeed = 5.0;control.zoomSpeed = 5;控制.panSpeed = 2;control.noZoom = false;control.noPan = false;control.staticMoving = true;control.dynamicDampingFactor = 0.3;场景 = 新的 THREE.Scene();场景添加(相机);//光var dirLight = new THREE.DirectionalLight(0xffffff);dirLight.position.set( 20, 20, 100 ).normalize();相机.添加( dirLight );相机.添加( dirLight.target );//质地var manager = new THREE.LoadingManager();manager.onProgress = 函数(项目,已加载,总计){console.log( 项目, 加载, 总计);};var 纹理 = 新的 THREE.Texture();var loader = new THREE.ImageLoader( manager );loader.load('bigthumbnail.jpg', function ( image ) {纹理.图像 = 图像;纹理.needsUpdate = true;});var loader = new THREE.OBJLoader()loader.load('Gamepad.obj', 函数(对象){object.position.y = 0;场景添加(对象);});//渲染器renderer = new THREE.WebGLRenderer( { antialias: false } );renderer.setSize( window.innerWidth, window.innerHeight );container = document.createElement('div');document.body.appendChild(容器);container.appendChild(renderer.domElement);统计=新统计();stats.domElement.style.position = '绝对';stats.domElement.style.top = '0px';container.appendChild(stats.domElement);//window.addEventListener('resize', onWindowResize, false );}函数 onWindowResize() {camera.aspect = window.innerWidth/window.innerHeight;相机.updateProjectionMatrix();renderer.setSize( window.innerWidth, window.innerHeight );control.handleResize();}函数动画(){requestAnimationFrame( 动画 );控制更新();renderer.render(场景,相机);stats.update();}</html>

我浏览了 Threejs.org 网站并查看了大部分示例.所有使用复杂颜色的示例都使用 .bin 文件或 .js 文件.所以我下载了 Python 2.7.6,安装了它并运行了 convert_obj_three.py.这生成了一个 .js 文件,但我不确定它的格式是否正确.不幸的是,convert_obj_three.py 给我的输出太大而无法发布.我的第二个问题是哪种文件格式最适合复杂的着色,比如铬蓝?.bin、.js 或者我可以使用 .obj 吗?如果使用 .js 是最好的方法,那么我如何可靠地将 .obj 文件转换为 .js?顺便说一句,我尝试使用convert_obj_three.py创建的.js,但网页一直是空白的.似乎我无法使用 THREE.JSONLoader() 加载 .js.

提前致谢.

解决方案

loader.load 函数执行后,你会得到一个 Threejs Object3D 对象.其中包含对象的网格.

所以你需要遍历它们来改变材质的颜色.代码将是这样的.

var loader = new THREE.OBJLoader()loader.load('Gamepad.obj', 函数(对象){object.traverse(函数(子){如果(子实例THREE.Mesh){child.material.ambient.setHex(0xFF0000);child.material.color.setHex(0x00FF00);}});object.position.y = 0;场景添加(对象);});

现在物体的材质有两个决定它的颜色的属性,你可以在代码 ambientcolor 中看到.

所以这就是说,如果在场景中你有白色 AmbientLight 对象将显示为红色(因为环境属性设置为 #FF0000)

如果物体被一些其他类型的光照亮,比如 pointlightdirectionalLight(如上面的例子),物体将显示为绿色(作为 color 设置为#00FF00).

现在最后一种情况,如果您说场景中有一个白色的 AmbientLight 和一个 DirectionalLight,那么该对象将显示为与 一样的黄色material.ambientmaterial.color 都将起作用,红色+绿色将呈现为黄色.希望这会有所帮助.

I am new to ThreeJS and have a simple question. I have the following code that will work properly, but I cannot add color to my .obj. The short and narrow of it is that I designed a game controller in Solidworks 2012, then I exported the CAD file as a .stl. I then used MeshLab to export the .stl as a .obj. Now I use the .obj in ThreeJS and it works, but I cannot for the life of me get color added to the .obj. Here is the code

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - loaders - vtk loader</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: #000;
                color: #fff;
                margin: 0px;
                overflow: hidden;
            }
            #info {
                color: #fff;
                position: absolute;
                top: 10px;
                width: 100%;
                text-align: center;
                z-index: 100;
                display:block;
            }
            #info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
        </style>
    </head>

    <body>
        <div id="info">
        <a href="" target="_blank">three.js</a> -
        vtk format loader test -
        model from <a href="" target="_blank">The GeorgiaTech Lagre Geometric Model Archive</a>,
        </div>

        <script src="three.min.js"></script>

        <script src="TrackballControls.js"></script>

        <script src="OBJLoader.js"></script>
        <script src="BinaryLoader.js"></script>
        <script src="Detector.js"></script>
        <script src="stats.min.js"></script>

        <script>

            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var container, stats;

            var camera, controls, scene, renderer;

            var cross;

            init();
            animate();

            function init() {

                camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01, 1e10 );
                camera.position.z = 200;
                camera.position.y = 200;

                controls = new THREE.TrackballControls( camera );

                controls.rotateSpeed = 5.0;
                controls.zoomSpeed = 5;
                controls.panSpeed = 2;

                controls.noZoom = false;
                controls.noPan = false;

                controls.staticMoving = true;
                controls.dynamicDampingFactor = 0.3;

                scene = new THREE.Scene();

                scene.add( camera );

                // light

                var dirLight = new THREE.DirectionalLight( 0xffffff );
                dirLight.position.set( 20, 20, 100 ).normalize();

                camera.add( dirLight );
                camera.add( dirLight.target );

                // texture

                var manager = new THREE.LoadingManager();
                manager.onProgress = function ( item, loaded, total ) {

                    console.log( item, loaded, total );

                };

                var texture = new THREE.Texture();

                var loader = new THREE.ImageLoader( manager );
                loader.load( 'bigthumbnail.jpg', function ( image ) {

                    texture.image = image;
                    texture.needsUpdate = true;

                } );

                var loader = new THREE.OBJLoader()
                loader.load( 'Gamepad.obj', function ( object ) {

                    object.position.y = 0;
                    scene.add( object );                

                } );
                // renderer

                renderer = new THREE.WebGLRenderer( { antialias: false } );
                renderer.setSize( window.innerWidth, window.innerHeight );

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

                stats = new Stats();
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.top = '0px';
                container.appendChild( stats.domElement );

                //

                window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize() {

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                renderer.setSize( window.innerWidth, window.innerHeight );

                controls.handleResize();

            }

            function animate() {

                requestAnimationFrame( animate );

                controls.update();
                renderer.render( scene, camera );

                stats.update();

            }

        </script>

    </body>
</html>

I have poured through the threejs.org website and looked at most of the examples. All of the examples that use complex colors use .bin files or .js files. So I downloaded Python 2.7.6, installed it and ran convert_obj_three.py. This generated a .js file, but I'm not sure it is correctly formatted. Unfortunately, The output that convert_obj_three.py gave me is too large to post. My Second question is which file format is best for complex coloring, like chrome blue? .bin, .js or can I use .obj? If using a .js is the best way to go then how can I reliably convert the .obj file to .js? By the way, I tried using the .js that was created by convert_obj_three.py, but the webpage is blank all the time. Seems I cannot load the .js using THREE.JSONLoader().

Thanks in advance.

解决方案

after loader.load function is executed you get a threejs Object3D object. which contains the meshes of your object .

so you need to traverse over them to change the color of the material. The code will be something like this.

var loader = new THREE.OBJLoader()
                loader.load( 'Gamepad.obj', function ( object ) {

                   object.traverse( function ( child ) {
                             if ( child instanceof THREE.Mesh ) {
                                  child.material.ambient.setHex(0xFF0000);
                                  child.material.color.setHex(0x00FF00);
                                 }
                             } );

                    object.position.y = 0;
                    scene.add( object );                
            } );

Now the object's material has two properties which decides its color as you may see in the code ambient and color .

So this is to say that if in the scene you have white AmbientLight the object will appear Red(because the ambient property is set to #FF0000)

If the object is luminated by some other type of light like pointlight or directionalLight (as in your above case) the objects will appear Green(as color is set to #00FF00).

Now the last case if you have say that you have one white AmbientLight and one DirectionalLight in the Scene, then the object will appear as yellow as both material.ambient and material.color both will come into play and Red+Green will render as Yellow. Hoping this helps.

这篇关于在 ThreeJS 中为 .obj 添加颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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