JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js"
}
}
</script>
CSS
body {
margin: 0;
}
button {
position: fixed;
top: 1em;
right: 1em;
}
JavaScript
import * as THREE from 'three';
// Custom ---
class CustomScene1 extends THREE.Scene {
constructor() {
super();
this.camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
// instantiate 3D objects...
//this.add(meshes);
}
//Do the scene stuff...
}
// init
const mainCamera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
mainCamera.position.z = 0.5;
let currentCamera = mainCamera;
const customScene = new CustomScene1();
const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -1
customScene.add(mesh);
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animation);
document.body.appendChild(renderer.domElement);
// animation
function animation(time) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render(customScene, currentCamera);
}
// Switch Camera UI
const button = document.createElement('button');
document.body.appendChild(button);
button.innerText = "Switch to Scene Camera";
button.onclick = () => {
const isMainCamera = currentCamera === mainCamera;
currentCamera = isMainCamera ? customScene.camera : mainCamera;
button.innerText = "Switch to " + (isMainCamera ? "Main Camera" : "Scene Camera")
}