Spaces:
Running
Running
<html> | |
<head> | |
<title>Three.js Scene and Animation Example</title> | |
<style> | |
body { | |
margin: 0; | |
padding: 0; | |
} | |
canvas { | |
display: block; | |
} | |
</style> | |
</head> | |
<body> | |
<script src="https://threejs.org/build/three.min.js"></script> | |
<script> | |
// Set up the scene, camera, and renderer | |
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); | |
// Add lighting to the scene | |
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); | |
scene.add(ambientLight); | |
const pointLight = new THREE.PointLight(0xffffff, 1); | |
pointLight.position.set(5, 5, 5); | |
scene.add(pointLight); | |
// Create a complex shaded shape geometry and material | |
const geometry = new THREE.TorusKnotGeometry(1, 0.4, 256, 32, 2, 3, 1); | |
const material = new THREE.MeshPhongMaterial({ | |
color: 0xffaaff, | |
specular: 0x999999, | |
shininess: 50, | |
flatShading: false, | |
}); | |
// Create a shape mesh and add it to the scene | |
const shape = new THREE.Mesh(geometry, material); | |
scene.add(shape); | |
// Set up animation loop | |
const animate = function () { | |
requestAnimationFrame(animate); | |
// Rotate the shape | |
shape.rotation.x += 0.01; | |
shape.rotation.y += 0.01; | |
// Move the camera in a circle around the shape | |
const time = Date.now() * 0.001; | |
const radius = 10; | |
camera.position.x = Math.sin(time) * radius; | |
camera.position.z = Math.cos(time) * radius; | |
camera.lookAt(new THREE.Vector3()); | |
// Update the lighting position to follow the camera | |
pointLight.position.copy(camera.position); | |
renderer.render(scene, camera); | |
}; | |
// Start the animation loop | |
animate(); | |
// Adjust camera position | |
camera.position.z = 10; | |
</script> | |
</body> | |
</html> | |