Skip to content

Instantly share code, notes, and snippets.

@yukiarimo
Created March 28, 2024 02:24
Show Gist options
  • Save yukiarimo/1031738166fc33cdf9cd3fce4ef7c511 to your computer and use it in GitHub Desktop.
Save yukiarimo/1031738166fc33cdf9cd3fce4ef7c511 to your computer and use it in GitHub Desktop.
Three JS Model Demo
import * as THREE from 'three';
import {
OrbitControls
} from 'https://unpkg.com/three/examples/jsm/controls/OrbitControls.js';
import {
GLTFLoader
} from 'https://unpkg.com/three/examples/jsm/loaders/GLTFLoader.js';
let camera, scene, renderer, model, controls;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.set(0, 150, 50); // Adjust camera position to better view the model
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0); // the default
// create a div element
const div = document.createElement('div');
// set id to the 3d-model
div.id = 'vr-model';
// append the renderer to the div
div.appendChild(renderer.domElement);
// append the div to the top of the body
document.body.insertBefore(div, document.body.firstChild);
controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, -20, -150);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2; // Prevent the camera from going below the ground
controls.minPolarAngle = Math.PI / 3; // Prevent the camera from going too high
const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 0).normalize();
scene.add(directionalLight);
// GLTFLoader to load a 3D model
const loader = new GLTFLoader();
loader.load('/static/js/untitled.glb', function (gltf) {
model = gltf.scene;
scene.add(model);
}, undefined, function (error) {
console.error(error);
});
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
// Required if controls.enableDamping or controls.autoRotate are set to true
controls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment