JSFiddle - React, Tailwind, and code Playground
HTML
<div class="depth"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
CSS
body { margin: 0; }
.depth {
position: fixed; top: 10px; right: 10px;
padding 10px;
background: rgba(0,0,0,0.4);
color: white;
}
Babel + JSX
const {
WebGLRenderer,
WebGLRenderTarget,
Scene,
PerspectiveCamera,
Vector2,
Vector3,
Vector4,
Ray,
AmbientLight,
DirectionalLight,
MeshDepthMaterial,
RGBADepthPacking,
Mesh,
SphereBufferGeometry,
MeshStandardMaterial,
OrbitControls,
FlatShading
} = THREE;
//
// ... global state
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
const mousePosition = new Vector2();
//
// .... setup renderer
const renderer = new WebGLRenderer({
alpha: true,
antialias: true,
logarithmicDepthBuffer: false
});
renderer.setSize(windowWidth, windowHeight);
const depthTarget = new WebGLRenderTarget(windowWidth, windowHeight);
//
// .... setup scene
const scene = (window.scene = new Scene());
//
// .... setup camera and controls
const aspect = windowWidth / windowHeight;
const camera = new PerspectiveCamera(70, aspect, 0.1, 200);
const controls = new OrbitControls(camera);
camera.position.set(-3, 3, 4);
camera.lookAt(new Vector3(0, 0, 0));
//
// .... setup lighting
const dirLight = new DirectionalLight();
dirLight.position.set(1, 0.4, 0.2);
scene.add(dirLight, new AmbientLight(0x444444));
//
// .... add objects
scene.add(
new Mesh(
new SphereBufferGeometry(1, 10, 5),
new MeshStandardMaterial({
shading: FlatShading,
color: 0xff2200,
transparent: true,
opacity: 0.8
})
)
);
const cursor = new Mesh(
new SphereBufferGeometry(0.1, 10, 5),
new MeshStandardMaterial({ color: 0xffffff })
);
scene.add(cursor);
//
// .... helper-function to retrieve depth
const getDepth = (function() {
const rgbaBuffer = new Uint8Array(4);
const v4 = new Vector4();
const unpackDownscale = 255 / 256;
const unpackFactors = new Vector4(
unpackDownscale / (256 * 256 * 256),
unpackDownscale / (256 * 256),
unpackDownscale / 256,
unpackDownscale
);
function unpackRGBAToDepth(buffer) {
return v4.fromArray(buffer).multiplyScalar(1 / 255).dot(unpackFactors);
}
function...