How do I make a mesh with an edgeGeometry always on top but still make outline behind the mesh hidden?

How to make the box on the right? I used depthTest false on the box and its outline to make it always on top of other mesh but the outline is now ignoring the box depth.

image

Here is the sample code the display the image on the left

Try pasting this code in your fiddle:

var camera, scene, renderer;
var geometry, material, greenMesh;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 5;

    scene = new THREE.Scene();

    geometry = new THREE.BoxGeometry( 1, 1, 1 );
    material = new THREE.MeshBasicMaterial({color: 0x00ff00,side:THREE.DoubleSide});
    greenMesh = new THREE.Mesh( geometry, material );
    var edgeMaterial = new THREE.LineBasicMaterial({color: 'black'});
    var edges = new THREE.EdgesGeometry(geometry);
    var wireframe = new THREE.LineSegments(edges, edgeMaterial);
    wireframe.renderOrder = 1;
    greenMesh.add(wireframe);
    greenMesh.renderOrder = 1;
    
    scene.add(greenMesh);
    
    material3 = new THREE.MeshStandardMaterial({emissive: 0x00ffff,side:THREE.DoubleSide});
    
    geometry3 = new THREE.BoxGeometry( 1.275,1.275,1 );

    blueMesh = new THREE.Mesh( geometry3, material3 );
    blueMesh.position.z = -1;
   
    scene.add(blueMesh);

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    greenMesh.rotation.x += 0.01;
    greenMesh.rotation.y += 0.02;

    renderer.render( scene, camera );

}

Or even better, add to your fiddle’s HTML code the following:

<script src="https://cdn.jsdelivr.net/npm/three@0.127/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.127/examples/js/controls/OrbitControls.min.js"></script>

and then add the new controls variable in your code:

var camera, scene, controls, renderer;
var geometry, material, greenMesh;

and then add the following line after the renderer creation:

    controls = new THREE.OrbitControls( camera, renderer.domElement );

This way you can use the mouse to rotate your boxes and see their position and size. Then keep changing any parameters in your code and re-run the fiddle to see the outcome.

    var edgeMaterial = new THREE.LineBasicMaterial({
      color: 'black',
      depthFunc:THREE.LessEqualDepth,
    });