Displaying background colour through transparent P

2019-01-15 09:47发布

问题:

I'm making a case builder using THREE.js, the basics are i want to be able to change the height/width/length of a box, rotate it around, and also change the background color of the box.

This is it so far: http://design365hosting.co.uk/casebuilder3D/

The dimension changing works, as does the dragging of the box, now i'm working with the background color change.

The way i want this to work is by using transparent PNGs as the faces of the box, and setting background colors so that this background colour shows through the transparent PNG.

This is how I'm currently doing it:

var texture = THREE.ImageUtils.loadTexture("images/crate.png");
materials.push(new THREE.MeshBasicMaterial({color:0xFF0000, map: texture}));

as you can see I set the material to have a background colour of red and overlay the transparent PNG, problem is, three.js seems to ignore the background colour and just show the transparent PNG, meaning no colour shows through.

The expected result should be a red box with the overlayed PNG.

Hope that made sense, can anyone help?

回答1:

Three.js MeshBasicMaterial does not support what you are trying to do. In MeshBasicMaterial, if the PNG is partially transparent, then the material will be partially transparent.

What you want, is the material to remain opaque, and the material color to show through instead.

You can do this with a custom ShaderMaterial. In fact, it is pretty easy. Here is the fragment shader:

uniform vec3 color;
uniform sampler2D texture;

varying vec2 vUv;

void main() {

    vec4 tColor = texture2D( texture, vUv );

    gl_FragColor = vec4( mix( color, tColor.rgb, tColor.a ), 1.0 );

}

And here is a Fiddle: http://jsfiddle.net/g5btunz9/

In the fiddle, the texture is a circle on a transparent background. You can see the red color of the material show through.

three.js r.72