Three.js png texture - alpha渲染为白色而不是透明

时间:2013-07-05 10:25:22

标签: three.js webgl

我正在创建一个立方体,我为它的每个面部应用了6种不同的纹理。每个纹理都是.png文件,包含透明部分。我也在为立方体应用一种颜色 - 我希望看到那种颜色透明。

问题:透明度呈现为白色,因此我看不到立方体的基色(如果我删除png纹理,则呈现正常)

如何让png透明度有效?我尝试使用一些材质设置,但没有一个让它透明。

创建多维数据集和材料的代码:

var geometry = new THREE.CubeGeometry(150, 200, 150, 2, 2, 2);
var materials = [];

// create textures array for all cube sides
for (var i = 1; i < 7; i++) {
   var img = new Image();
   img.src = 'img/s' + i + '.png';
   var tex = new THREE.Texture(img);
   img.tex = tex;

   img.onload = function () {
      this.tex.needsUpdate = true;
   };

   var mat = new THREE.MeshBasicMaterial({color: 0x00ff00, map: tex, transparent: true, overdraw: true });
   materials.push(mat);
}
cube = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
cube.position.y = 150;
scene.add(cube);

修改

下面的图片显示了问题 - 使用sendhanal解决方案,左边的纹理现在呈现正常 - 它是一个没有透明度的png图像 - 我在代码中设置了透明度

materialArray.push(new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('img/s2.png'), transparent: true, opacity: 0.9, color: 0xFF0000 }));

正确的纹理也是一个png图像 - 只有它有一个透明区域(所有呈现白色应该是纯红色,因为它是透明的,应该从立方体中获取颜色?)。如何使白色部分透明?

enter image description here

1 个答案:

答案 0 :(得分:26)

材质的不透明度属性可以帮到你。以下是示例代码段:

var materialArray = [];
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xpos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/xneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/ypos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/yneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zpos.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/zneg.png' ), transparent: true, opacity: 0.5, color: 0xFF0000 }));
var MovingCubeMat = new THREE.MeshFaceMaterial(materialArray);
var MovingCubeGeom = new THREE.CubeGeometry( 50, 50, 50, 1, 1, 1, materialArray );
MovingCube = new THREE.Mesh( MovingCubeGeom, MovingCubeMat );
MovingCube.position.set(0, 25.1, 0);
scene.add( MovingCube );    

http://threejs.org/docs/#Reference/Materials/Material关键是设置透明属性为true并将不透明度设置为0.5(例如)。 添加第二个完全适合内部的立方体,没有透明度,来自@WestLangley(Three.js canvas render and transparency)的想法

backCube = new THREE.Mesh( MovingCubeGeom, new THREE.MeshBasicMaterial( { color: 0xFF0000 }) );
backCube.position.set(0, 25.1, 0);
backCube.scale.set( 0.99, 0.99, 0.99 );
scene.add( backCube );