-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
102 lines (82 loc) · 2.81 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @filename main.js
* @brief Things that every three.js projects needs
* @author Sarah Rosanna Busch
* @version 0.1
* @date 26 April 2024
*/
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
let container, camera, renderer, scene, controls;
let width, height; //container dimensions
let tick = 0;
init();
function init() {
//dom elements and event listeners
container = document.getElementById('container');
width = container.clientWidth;
height = container.clientHeight;
// camera
camera = new THREE.PerspectiveCamera( 50, width / height, 0.1, 1000 );
camera.position.z = 5;
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( width, height );
renderer.outputEncoding = THREE.sRGBEncoding;
container.appendChild( renderer.domElement );
// scene
scene = new THREE.Scene();
const light = new THREE.AmbientLight( 0x404040 ); // soft white light
scene.add( light );
// controls
controls = new OrbitControls( camera, renderer.domElement );
controls.autoRotate = true;
// listeners
window.addEventListener( 'resize', onWindowResize );
Object.assign( window, { scene } );
initObjects(() => {
console.log('scene is loaded');
animate();
});
}
function initObjects(callback) {
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshNormalMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
callback();
}
function animate(time) { //ms
if(time >= (tick + 16)) { //enforcing 60fps so animation is same speed on all devices
tick = time;
if(resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
controls.update();
camera.updateProjectionMatrix();
renderer.render( scene, camera );
}
requestAnimationFrame( animate );
}
// *********** HELPERS **************
//return true if the canvas resolution needs to change
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
width = canvas.clientWidth;
height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function onWindowResize() {
width = window.innerWidth;
height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
}