Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

three.js - Displaying background colour through transparent PNG on material?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 by modifying the material's shader:

var material = new THREE.MeshPhongMaterial( {
    color: 0x0080ff,
    map: texture
} );

material.onBeforeCompile = function ( shader ) {

    var custom_map_fragment = THREE.ShaderChunk.map_fragment.replace(

        `diffuseColor *= texelColor;`,

        `diffuseColor = vec4( mix( diffuse, texelColor.rgb, texelColor.a ), opacity );`

    );

    shader.fragmentShader = shader.fragmentShader.replace( '#include <map_fragment>', custom_map_fragment );

};

And here is a Fiddle: https://jsfiddle.net/17jmgn6r/

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

three.js r.125


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...