Setting Up the Scene
Before implementing camera switching, you need a Three.js scene with at least two cameras. Here’s how to set up a basic scene:
// Scene, renderer, and common setup
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Perspective Camera
const perspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
perspectiveCamera.position.set(0, 1, 5);
// Orthographic Camera
const aspect = window.innerWidth / window.innerHeight;
const orthographicCamera = new THREE.OrthographicCamera(-aspect * 5, aspect * 5, 5, -5, 0.1, 1000);
orthographicCamera.position.set(0, 5, 5);
orthographicCamera.lookAt(0, 0, 0);
// Default active camera
let activeCamera = perspectiveCamera;
// Add objects to the scene
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
Implementing Camera Switching
To enable camera switching, you can use a keypress or a button in the UI. Below is an example using a keyboard event:
// Event listener for switching cameras
document.addEventListener(‘keydown’, (event) => {
if (event.key === ‘c’) {
activeCamera = (activeCamera === perspectiveCamera) ? orthographicCamera : perspectiveCamera;
}
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, activeCamera);
}
animate();