简体   繁体   English

在three.js中更改颜色和纹理

[英]Change collor and texture in three.js

I'm trying to change the color and image of a material but I'm not getting it, I'm using the following code: 我正在尝试更改材料的颜色和图像,但我没有得到,我正在使用以下代码:

elf.material = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture('3d/caneca/e.jpg')});

but it did not work. 但它没有用。 In the object I have 3 materials, I wanted to change the color of one and replace the texture of another. 在该对象中,我有3种材质,我想更改一种材质的颜色并替换另一种材质的纹理。

You can change the material of an object at run time. 您可以在运行时更改对象的材质。 All you need to do is, create a material by specifying the options and assign it to the object. 您需要做的就是通过指定选项创建材料并将其分配给对象。 For example the following code will create a 'MeshStandardMaterial' with white color and other properties as specified. 例如,以下代码将创建带有白色和指定其他属性的“ MeshStandardMaterial”。 It will also have a texture which you have loaded. 它还将具有您已加载的纹理。 Consider ' box ' as the object on which the material should be attached. 将“ 盒子 ”视为应在其上附着材料的对象。

var material = new THREE.MeshStandardMaterial( { color: 0xffffff, side: THREE.FrontSide, opacity: 0.3, transparent: true, vertexColors: THREE.FaceColors, map : <THE TEXTURE YOU HAVE LOADED> } );

As a better approach, you can load the texture using TextureLoader , and create a material when the texture is loaded. 作为更好的方法,可以使用TextureLoader加载纹理,并在加载纹理时创建材质。 Following code explains that. 以下代码对此进行了说明。

var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    var material = new THREE.MeshPhongMaterial( { map : texture, color : 0xff0000 } );
    box.material = material;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/crate.png', onLoad, onProgress, onError );

You can also change the color and texture of the material without creating a new material , 您也可以更改材质的颜色和纹理,而无需创建新材质

to change only the color, 只改变颜色

box.material.color.setHex( 0xff0000 );// will set red color for the box

or to change the texture, 或更改纹理,

var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    box.material.map = texture;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/Dice-Blue-5.png', onLoad, onProgress, onError );

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

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