JSFiddle - React, Tailwind, and code Playground
HTML
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js",
"three/addons/": "https://unpkg.com/three/examples/jsm/"
}
}
</script>
<body>
<div class="menu-container">
</div>
</body>
CSS
body {
margin: 0;
position: relative;
}
div {
background-color: red;
opacity: 0.3;
width: 10px;
height: 10px;
position: absolute;
left: 50%;
top: 50%;
}
JavaScript
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
const cubeSize = new THREE.Vector3();
const box3 = new THREE.Box3();
box3.setFromObject(cube);
cube.updateMatrixWorld(true)
box3.applyMatrix4(cube.matrixWorld);
box3.getSize(cubeSize);
cubeSize.project(camera);
/* cube.position.z += 0.01; */
console.log(cubeSize);
const x = (cubeSize.x * 0.5 + 0.5) * (window.innerWidth / 2);
const y = (cubeSize.y * -0.5 + 0.5) * (window.innerHeight / 2);
const container = document.querySelector('.menu-container');
if (container) {
container.style.width = `${x}px`;
container.style.height = `${y}px`;
container.style.transform = `translate(-50%, -50%)`;
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();