JSFiddle - React, Tailwind, and code Playground
by dumptyd
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>
JavaScript
const width = Math.min(window.innerHeight, window.innerWidth);
const height = width;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height - 4);
document.body.appendChild(renderer.domElement);
const cuber = d => {
const cubeGeometry = new THREE.BoxGeometry(d, d, d);
const cubeMaterial = new THREE.MeshBasicMaterial({ color: '#000' });
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
const borderGeometry = new THREE.EdgesGeometry(cubeGeometry);
const borderMaterial = new THREE.LineBasicMaterial({ color: 0xffffff, linewidth: 1 });
const wireframe = new THREE.LineSegments(borderGeometry, borderMaterial);
cube.add(wireframe);
return cube;
};
const visibleHeightAtZDepth = (depth, camera) => {
// compensate for cameras not positioned at z=0
const cameraOffset = camera.position.z;
if ( depth < cameraOffset ) depth -= cameraOffset;
else depth += cameraOffset;
// vertical fov in radians
const vFOV = camera.fov * Math.PI / 180;
// Math.abs to ensure the result is always positive
return 2 * Math.tan( vFOV / 2 ) * Math.abs( depth );
};
const visibleWidthAtZDepth = (depth, camera) => {
const height = visibleHeightAtZDepth(depth, camera);
return height * camera.aspect;
};
const toLocal = (x, y) => {
const vec = new THREE.Vector3();
const pos = new THREE.Vector3();
vec.set((x / width) * 2 - 1, -(y / height) * 2 + 1, 0.5);
vec.unproject(camera);
vec.sub(camera.position).normalize();
const distance = (0 - camera.position.z) / vec.z;
pos.copy(camera.position).add(vec.multiplyScalar(distance));
return [pos.x, pos.y];
};
camera.position.z = 5;
const zWidth = visibleWidthAtZDepth(-5, camera);
const zHeight = visibleHeightAtZDepth(-5, camera)
const cubeCounts = 13;
let cubeDimensions = zWidth / cubeCounts;
const cubeGap = cubeDimensions * .25;
cubeDimensions -=...