Three JSFiddle Skeleton
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.skypack.dev/three@0.144.0/build/three.module",
"three/": "https://cdn.skypack.dev/three@0.144.0/"
}
}
</script>
CSS
* {
box-sizing: border-box;
text-rendering: optimizeLegibility;
font-kerning: auto;
outline: none;
}
html {
font-family: sans-serif;
}
body {
margin: 0;
}
JavaScript
import * as THREE from 'three'
const scene = new THREE.Scene()
const cameraZ = 300;
const fieldOfView = 10;
const nearClippingPage = 0.5;
const farClippingPage = 500;
const persCamera = new THREE.PerspectiveCamera(
fieldOfView,
window.innerWidth / window.innerHeight,
nearClippingPage,
farClippingPage
);
let maxDim = Math.max(window.innerHeight, window.innerWidth)
const orthCamera = new THREE.OrthographicCamera(
- window.innerWidth * 26 / maxDim,
window.innerWidth * 26 / maxDim,
window.innerHeight * 26 / maxDim,
- window.innerHeight * 26 / maxDim,
-100, 300)
let camera = persCamera
camera.position.z = cameraZ
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
let type = "pers"
const cubeHeight = 100
for (let i = 0; i < 10; i += 1) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(7,7,cubeHeight),
new THREE.MeshBasicMaterial({
color: 0x00ff00
})
)
cube.position.x = -50 + i * 10
cube.position.y = i * 2
cube.name = "cube"
scene.add(cube)
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(1),
new THREE.MeshBasicMaterial({
color: 0xff0000
})
)
sphere.position.x = cube.position.x
sphere.position.y = cube.position.y
sphere.position.z = cubeHeight / 2
sphere.name = "sphere"
scene.add(sphere)
}
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
render()
}, false)
function switchCamera(){
console.log('switching')
const cameraPosition = camera.position.clone();
const cameraMatrix = camera.matrix.clone();
if (type == 'orth'){
camera = persCamera;
type = 'pers'
} else if (type = 'pers'){
camera = orthCamera;
type = 'orth'
}
camera.position.copy(cameraPosition)
...