Certainly! Below is a Three.js script that creates a cube, spins the camera around it, and morphs the cube's edges between two states as the camera moves. The animation runs at 20 frames per second.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Transforming Cube with Spinning Camera</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<!-- Include Three.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script>
// Scene, Camera, and Renderer setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
const aspect = window.innerWidth / window.innerHeight;
const camera = new THREE.PerspectiveCamera(45, aspect, 0.1, 1000);
camera.position.set(5, 5, 5); // Initial position
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Ambient Light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
// Directional Light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 7.5);
scene.add(directionalLight);
// Geometry: Create two cube geometries for morphing
const geometry1 = new THREE.BoxGeometry(2, 2, 2); // Original cube
const geometry2 = new THREE.BoxGeometry(2, 2, 2); // Cube to morph into
// Modify the second geometry to create a distorted cube
const positionAttribute = geometry2.getAttribute('position');
const vertexCount = positionAttribute.count;
for (let i = 0; i < vertexCount; i++) {
const ix = i * 3;
const iy = i * 3 + 1;
const iz = i * 3 + 2;
// Randomly scale each vertex position to distort the cube
positionAttribute.array[ix] *= (Math.random() * 1.5 + 0.5);
positionAttribute.array[iy] *= (Math.random() * 1.5 + 0.5);
positionAttribute.array[iz] *= (Math.random() * 1.5 + 0.5);
}
// Assign the distorted geometry as a morph target
geometry1.morphAttributes.position = [geometry2.getAttribute('position')];
// Material with morphTargets enabled
const material = new THREE.MeshNormalMaterial({ morphTargets: true });
// Create mesh with the geometry and material
const mesh = new THREE.Mesh(geometry1, material);
scene.add(mesh);
// Add edges to the cube for better visualization
const edges = new THREE.EdgesGeometry(mesh.geometry);
const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0x000000 }));
mesh.add(line);
// Animation variables
let angle = 0;
const frameRate = 20; // Frames per second
const frameDelay = 1000 / frameRate; // Time between frames in ms
let lastFrameTime = 0;
// Animation loop
function animate(time) {
requestAnimationFrame(animate);
if (time - lastFrameTime >= frameDelay) {
// Spin the camera around the cube
angle += 0.02;
camera.position.x = 5 * Math.cos(angle);
camera.position.z = 5 * Math.sin(angle);
camera.lookAt(scene.position);
// Morph the cube between the two geometries based on the camera angle
const influence = (Math.sin(angle * 2) + 1) / 2; // Value between 0 and 1
mesh.morphTargetInfluences[0] = influence;
// Render the scene
renderer.render(scene, camera);
// Update the time of the last rendered frame
lastFrameTime = time;
}
}
// Start the animation
animate(0);
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
const aspect = window.innerWidth / window.innerHeight;
camera.aspect = aspect;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>
Explanation
-
Scene Setup:
- We create a
Scene, Camera, and Renderer to set up the basic Three.js environment.
- The camera is positioned initially at
(5, 5, 5) and looks at the center of the scene.
-
Lighting:
- An
AmbientLight and DirectionalLight illuminate the scene, so the cube is visible.
-
Geometry and Morphing:
- Two cube geometries (
geometry1 and geometry2) are created. geometry1 is a standard cube.
geometry2 is modified by randomly scaling its vertices, creating a distorted version of the cube.
- The distorted geometry is assigned as a morph target to
geometry1.
- A
MeshNormalMaterial with morphTargets enabled allows the cube to morph between the two geometries.
-
Edges Visualization:
- An
EdgesGeometry and LineSegments are added to the cube to make its edges visible, enhancing the transformation effect.
-
Animation Loop:
- The
animate function is called on each frame using requestAnimationFrame.
- To achieve 20 frames per second, we check if enough time (
frameDelay) has passed since the last frame.
- The camera spins around the cube by updating its
position.x and position.z in a circular path.
- The cube's morph influence is updated based on the
angle, causing it to morph between the two states as the camera moves.
- The scene is rendered with the updated camera and cube state.
-
Responsive Design:
- An event listener for
resize adjusts the camera and renderer when the browser window is resized.
How It Works
-
Camera Rotation: The camera moves in a circle around the cube, providing the spinning effect.
-
Cube Morphing: The morphTargetInfluences property controls the interpolation between the original cube and the distorted cube. As the camera spins, this value changes smoothly, blending the cube between the two shapes.
-
Synchronization: The morphing is synchronized with the camera's rotation by using the angle variable.
-
Performance: By controlling the frame rate, we ensure the animation runs at a consistent 20 frames per second.
Customization
-
Adjusting the Morphing Effect: You can modify how the cube morphs by changing the distortion applied to geometry2. For example, you can apply different transformations or use multiple morph targets.
-
Changing the Frame Rate: To adjust the frame rate, change the frameRate variable. Ensure that the animations appear smooth at the desired rate.
-
Camera Path: The camera's path can be altered to different shapes (e.g., elliptical) by modifying the camera.position calculations.
Running the Code
- Copy the above code into a new HTML file.
- Open the file in a web browser that supports WebGL (most modern browsers do).
- You should see a cube in the center of the screen, with the camera spinning around it and the cube's edges transforming as it rotates.
Enjoy experimenting with Three.js and creating dynamic 3D animations!