Interactive Rubik's Cube with Three.js
Here's a complete, self-contained HTML file that creates an interactive Rubik's Cube visualization with realistic lighting and controls:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Rubik's Cube</title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #1a1a1a;
color: white;
overflow: hidden;
}
#canvas-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
padding: 15px;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 10px;
max-width: 80%;
}
button {
padding: 10px 15px;
border: none;
border-radius: 5px;
background-color: #4a4a4a;
color: white;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #5a5a5a;
}
.face-btn {
min-width: 40px;
}
#scramble-btn, #solve-btn {
background-color: #2c3e50;
}
#scramble-btn:hover, #solve-btn:hover {
background-color: #34495e;
}
#status {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
background-color: rgba(0, 0, 0, 0.7);
border-radius: 5px;
font-size: 18px;
}
h1 {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
margin: 0;
font-size: 24px;
color: #fff;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}
</style>
</head>
<body>
<h1>Interactive Rubik's Cube</h1>
<div id="canvas-container"></div>
<div id="status">Cube is solved</div>
<div id="controls">
<button class="face-btn" id="U">U</button>
<button class="face-btn" id="Uprime">U′</button>
<button class="face-btn" id="D">D</button>
<button class="face-btn" id="Dprime">D′</button>
<button class="face-btn" id="L">L</button>
<button class="face-btn" id="Lprime">L′</button>
<button class="face-btn" id="R">R</button>
<button class="face-btn" id="Rprime">R′</button>
<button class="face-btn" id="F">F</button>
<button class="face-btn" id="Fprime">F′</button>
<button class="face-btn" id="B">B</button>
<button class="face-btn" id="Bprime">B′</button>
<button id="scramble-btn">Scramble</button>
<button id="solve-btn">Solve</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script>
// Main application
class RubiksCube {
constructor() {
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x1a1a1a);
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera.position.set(5, 5, 7);
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.shadowMap.enabled = true;
document.getElementById('canvas-container').appendChild(this.renderer.domElement);
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.05;
this.cubeGroup = new THREE.Group();
this.scene.add(this.cubeGroup);
this.cubies = [];
this.moveHistory = [];
this.isAnimating = false;
this.solving = false;
this.colors = {
right: 0xff4136, // Red
left: 0xff851b, // Orange
up: 0xffffff, // White
down: 0xffff00, // Yellow
front: 0x2ecc40, // Green
back: 0x0074d9 // Blue
};
this.setupLights();
this.createCube();
this.animate();
window.addEventListener('resize', () => this.onWindowResize());
this.setupEventListeners();
}
setupLights() {
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 7);
directionalLight.castShadow = true;
this.scene.add(directionalLight);
const backLight = new THREE.DirectionalLight(0xffffff, 0.3);
backLight.position.set(-5, -5, -5);
this.scene.add(backLight);
}
createCube() {
const geometry = new THREE.BoxGeometry(0.9, 0.9, 0.9);
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
// Skip the inner cube
if (x === 0 && y === 0 && z === 0) continue;
const materials = [];
// Right face (x = 1)
materials.push(x === 1 ? new THREE.MeshLambertMaterial({ color: this.colors.right }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
// Left face (x = -1)
materials.push(x === -1 ? new THREE.MeshLambertMaterial({ color: this.colors.left }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
// Top face (y = 1)
materials.push(y === 1 ? new THREE.MeshLambertMaterial({ color: this.colors.up }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
// Bottom face (y = -1)
materials.push(y === -1 ? new THREE.MeshLambertMaterial({ color: this.colors.down }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
// Front face (z = 1)
materials.push(z === 1 ? new THREE.MeshLambertMaterial({ color: this.colors.front }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
// Back face (z = -1)
materials.push(z === -1 ? new THREE.MeshLambertMaterial({ color: this.colors.back }) :
new THREE.MeshLambertMaterial({ color: 0x111111 }));
const cubie = new THREE.Mesh(geometry, materials);
cubie.position.set(x, y, z);
cubie.userData = {
originalPosition: new THREE.Vector3(x, y, z),
originalRotation: new THREE.Euler(0, 0, 0),
solved: true
};
this.cubeGroup.add(cubie);
this.cubies.push(cubie);
}
}
}
}
getCubiesByFace(face) {
const cubies = [];
const axis = face[0];
const direction = face.length > 1 && face[1] === "'" ? -1 : 1;
for (const cubie of this.cubies) {
let include = false;
switch (axis) {
case 'U': include = cubie.position.y === 1; break;
case 'D': include = cubie.position.y === -1; break;
case 'L': include = cubie.position.x === -1; break;
case 'R': include = cubie.position.x === 1; break;
case 'F': include = cubie.position.z === 1; break;
case 'B': include = cubie.position.z === -1; break;
}
if (include) {
cubies.push(cubie);
}
}
return cubies;
}
rotateFace(face, isPrime = false, animate = true) {
if (this.isAnimating) return;
const cubies = this.getCubiesByFace(face);
const axis = face[0];
const angle = (Math.PI / 2) * (isPrime ? -1 : 1);
if (animate) {
this.isAnimating = true;
this.animateRotation(cubies, axis, angle, () => {
this.isAnimating = false;
this.updateSolvedStatus();
});
} else {
this.applyRotation(cubies, axis, angle);
this.updateSolvedStatus();
}
if (!this.solving) {
this.moveHistory.push({ face, isPrime });
}
}
animateRotation(cubies, axis, angle, callback) {
const duration = 300; // milliseconds
const steps = 30; // number of animation steps
const stepAngle = angle / steps;
let currentStep = 0;
const animate = () => {
if (currentStep < steps) {
this.applyRotation(cubies, axis, stepAngle);
currentStep++;
requestAnimationFrame(animate);
} else {
callback();
}
};
animate();
}
applyRotation(cubies, axis, angle) {
const rotationMatrix = new THREE.Matrix4();
switch (axis) {
case 'U':
case 'D':
rotationMatrix.makeRotationY(axis === 'U' ? -angle : angle);
break;
case 'L':
case 'R':
rotationMatrix.makeRotationX(axis === 'R' ? -angle : angle);
break;
case 'F':
case 'B':
rotationMatrix.makeRotationZ(axis === 'F' ? angle : -angle);
break;
}
for (const cubie of cubies) {
// Apply rotation to position
cubie.position.applyMatrix4(rotationMatrix);
// Round positions to avoid floating point errors
cubie.position.x = Math.round(cubie.position.x * 100) / 100;
cubie.position.y = Math.round(cubie.position.y * 100) / 100;
cubie.position.z = Math.round(cubie.position.z * 100) / 100;
// Apply rotation to the cubie itself
switch (axis) {
case 'U':
case 'D':
cubie.rotateY(axis === 'U' ? angle : -angle);
break;
case 'L':
case 'R':
cubie.rotateX(axis === 'R' ? angle : -angle);
break;
case 'F':
case 'B':
cubie.rotateZ(axis === 'F' ? -angle : angle);
break;
}
}
}
scramble() {
if (this.isAnimating || this.solving) return;
const moves = ['U', 'U\'', 'D', 'D\'', 'L', 'L\'', 'R', 'R\'', 'F', 'F\'', 'B', 'B\''];
const numMoves = 20;
this.moveHistory = [];
const performMove = (index) => {
if (index >= numMoves) return;
const randomMove = moves[Math.floor(Math.random() * moves.length)];
const face = randomMove[0];
const isPrime = randomMove.length > 1;
this.rotateFace(face, isPrime, true);
setTimeout(() => {
performMove(index + 1);
}, 350);
};
performMove(0);
}
solve() {
if (this.isAnimating || this.solving || this.moveHistory.length === 0) return;
this.solving = true;
const statusElement = document.getElementById('status');
statusElement.textContent = "Solving...";
const performReverseMove = () => {
if (this.moveHistory.length === 0 || !this.solving) {
this.solving = false;
statusElement.textContent = "Cube is solved";
return;
}
const move = this.moveHistory.pop();
const reverseFace = move.face;
const reverseIsPrime = !move.isPrime;
this.rotateFace(reverseFace, reverseIsPrime, true);
setTimeout(performReverseMove, 500);
};
setTimeout(performReverseMove, 500);
}
updateSolvedStatus() {
const statusElement = document.getElementById('status');
const tolerance = 0.1;
for (const cubie of this.cubies) {
const pos = cubie.position;
const origPos = cubie.userData.originalPosition;
const positionMatch =
Math.abs(pos.x - origPos.x) < tolerance &&
Math.abs(pos.y - origPos.y) < tolerance &&
Math.abs(pos.z - origPos.z) < tolerance;
// Check if rotation is approximately identity
const rotationMatch =
Math.abs(cubie.rotation.x) % (Math.PI * 2) < tolerance &&
Math.abs(cubie.rotation.y) % (Math.PI * 2) < tolerance &&
Math.abs(cubie.rotation.z) % (Math.PI * 2) < tolerance;
cubie.userData.solved = positionMatch && rotationMatch;
if (!cubie.userData.solved) {
statusElement.textContent = "Cube is scrambled";
return;
}
}
statusElement.textContent = "Cube is solved";
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate() {
requestAnimationFrame(() => this.animate());
this.controls.update();
this.renderer.render(this.scene, this.camera);
}
setupEventListeners() {
document.getElementById('U').addEventListener('click', () => this.rotateFace('U', false, true));
document.getElementById('Uprime').addEventListener('click', () => this.rotateFace('U', true, true));
document.getElementById('D').addEventListener('click', () => this.rotateFace('D', false, true));
document.getElementById('Dprime').addEventListener('click', () => this.rotateFace('D', true, true));
document.getElementById('L').addEventListener('click', () => this.rotateFace('L', false, true));
document.getElementById('Lprime').addEventListener('click', () => this.rotateFace('L', true, true));
document.getElementById('R').addEventListener('click', () => this.rotateFace('R', false, true));
document.getElementById('Rprime').addEventListener('click', () => this.rotateFace('R', true, true));
document.getElementById('F').addEventListener('click', () => this.rotateFace('F', false, true));
document.getElementById('Fprime').addEventListener('click', () => this.rotateFace('F', true, true));
document.getElementById('B').addEventListener('click', () => this.rotateFace('B', false, true));
document.getElementById('Bprime').addEventListener('click', () => this.rotateFace('B', true, true));
document.getElementById('scramble-btn').addEventListener('click', () => this.scramble());
document.getElementById('solve-btn').addEventListener('click', () => this.solve());
}
}
// Initialize the application when the page loads
window.addEventListener('load', () => {
const rubiksCube = new RubiksCube();
});
</script>
</body>
</html>
Features
This implementation includes:
-
Realistic 3D Rubik's Cube with 27 individual cubies and standard coloring
-
Interactive Controls:
- Orbit controls for rotating and zooming the view
- Buttons for all face rotations (U, U′, D, D′, L, L′, R, R′, F, F′, B, B′)
- Scramble button to randomize the cube
- Solve button to automatically reverse the moves
-
Visual Features:
- Realistic lighting with ambient and directional lights
- Smooth animations for all rotations
- Status indicator showing if the cube is solved or scrambled
-
Functional Logic:
- Move history tracking
- Solved state detection with position and rotation tolerance checking
- Automatic solving by