JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/npm/three@0.120.1/build/three.js"></script>
CSS
body {
margin: 0;
}
canvas {
display: block;
}
JavaScript
let camera, scene, renderer, mesh;
let raycaster, mouse, currentIntersection;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 4;
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
scene = new THREE.Scene();
const geometry = new THREE.BoxBufferGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
material.userData.originalColor = new THREE.Color( 0xffff00 );
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.addEventListener('pointermove', onPointerMove, false);
}
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render(scene, camera);
}
function onPointerMove(event) {
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(scene, true);
if (intersects.length > 0) {
currentIntersection = intersects[0].object;
currentIntersection.material.color.set(0xff0000);
} else {
if (currentIntersection !== null) {
currentIntersection.material.color.copy( currentIntersection.material.userData.originalColor );
currentIntersection = null;
}
}
}