(Attempt 1) ThreeJS Fragment shader fade in and out at a specified z position

An attempt 1 at getting ThreeJS Fragment shader to fade in and out at a specified z position...

by AllForTheCode

HTML

<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
    
<script type="importmap">
	{
		"imports": {
			"three": "https://unpkg.com/three/build/three.module.js"
		}
	}
</script>
<div id="debug">
  <div id="debug1">x</div>
</div>

SCSS

html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#debug {
  position: absolute;
  left: 5px;
  top: 5px;
  z-index: 50;

  div {
    display: table;
    background: none;
    color: RGBA(255, 255, 255, 0.9);
  }
}

JavaScript

import * as THREE from 'three';

const db1 = document.getElementById("debug1");

const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 50);
camera.position.set(-2, 2, 2);
/* camera.position.z = 1; */

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const material = new THREE.MeshBasicMaterial({
  transparent: true
});
material.onBeforeCompile = function(m) {
  m.fragmentShader = `void main() {
  	float z = gl_FragCoord.z / gl_FragCoord.w; // get z of pixel
    float a = 1.0; // var init
    if( z > 0.0 ) {
    	// make transparency when z > z:0.0
      a = 1.0;
    } else {
    	a = 0.1;
    }
  	gl_FragColor = vec4( vec3( z ), a );
  }`;
};

const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const gridHelper = new THREE.GridHelper(1000, 1000);
scene.add(gridHelper);

const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animation);
renderer.domElement.style.zIndex = 10;
document.body.appendChild(renderer.domElement);


function animation(time) {

  const a = time / 3000;
  mesh.position.set(
    0, 0, Math.sin(a) * 10, 0
  );
  camera.lookAt(mesh.position);

  // Debug
  db1.innerHTML = `Z: ${mesh.position.z.toFixed(3)}`;

  renderer.render(scene, camera);

}