Skip to content

Instantly share code, notes, and snippets.

@abhi-io
Created February 27, 2024 15:38
Show Gist options
  • Save abhi-io/d631a2d3b3c9043475a122395b627f6b to your computer and use it in GitHub Desktop.
Save abhi-io/d631a2d3b3c9043475a122395b627f6b to your computer and use it in GitHub Desktop.
threeJs - Basic3d
import React, { useEffect } from 'react';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
function Basic3d() {
useEffect(() => {
// Scene
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xaaaaaa); // Optional: Change scene background
// Camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 1, 2); // Adjust camera position as needed
// Renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// OrbitControls setup
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Optional: For an inertial damping effect
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// GLTF Loader
const loader = new GLTFLoader();
loader.load(
'Apartment2.glb', // Assuming the model is in the public folder
function (gltf) {
const model = gltf.scene; // This is your model
// Scale down the model
model.scale.set(0.01, 0.01, 0.01); // Adjust these values as needed
scene.add(model);
},
undefined, // We are not using the onProgress callback
function (error) {
console.error('An error happened', error);
}
);
// OrbitControls (optional, for camera control)
// Uncomment these lines if you have installed OrbitControls
// import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// const controls = new OrbitControls(camera, renderer.domElement);
// controls.update();
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Required if controls.enableDamping or controls.autoRotate are set to true
controls.update();
renderer.render(scene, camera);
}
animate();
// Handle window resize
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
// Cleanup
return () => {
document.body.removeChild(renderer.domElement);
};
}, []);
return null; // We don't return any JSX since Three.js manipulates the DOM directly
}
export default Basic3d;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment