three.js ~ example ~ Mr.doob

2012-01-05 ~

by Umair Rafiq

HTML

<div id="container"></div>

JavaScript

// Set up Three.js scene
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.getElementById('container').appendChild(renderer.domElement);

// Create cube geometry and material
const geometry = new THREE.BoxGeometry(1, 1, 1);
const materials = [
    new THREE.MeshBasicMaterial({ color: 0xff0000 }), // Right side
    new THREE.MeshBasicMaterial({ color: 0x00ff00 }), // Left side
    new THREE.MeshBasicMaterial({ color: 0x0000ff }), // Top side
    new THREE.MeshBasicMaterial({ color: 0xffff00 }), // Bottom side
    new THREE.MeshBasicMaterial({ color: 0x00ffff }), // Front side
    new THREE.MeshBasicMaterial({ color: 0xff00ff })  // Back side
];
const cube = new THREE.Mesh(geometry, materials);
scene.add(cube);

// Set up mouse controls
const mouse = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const targetRotation = new THREE.Vector2(0, 0);
const targetRotationOnMouseDown = new THREE.Vector2(0, 0);
const windowHalfX = window.innerWidth / 2;
const windowHalfY = window.innerHeight / 2;

document.addEventListener('mousemove', onDocumentMouseMove, false);

function onDocumentMouseMove(event) {
    mouse.x = (event.clientX - windowHalfX) / 2;
    mouse.y = (event.clientY - windowHalfY) / 2;
}

// Render loop
function animate() {
    requestAnimationFrame(animate);

    // Rotate cube based on mouse position
    targetRotation.x = (mouse.x - targetRotationOnMouseDown.x) * 0.02;
    targetRotation.y = (mouse.y - targetRotationOnMouseDown.y) * 0.02;
    cube.rotation.x += 0.05 * (targetRotation.y - cube.rotation.x);
    cube.rotation.y += 0.05 * (targetRotation.x - cube.rotation.y);

    renderer.render(scene, camera);
}

animate();