Reputation: 111
I have some code for importing a 3D model (locally saved) and rendering it inside of my site via Qwik and Three js. The only problem is, that it causes the site performance to crash astronomically and even reloading or scrolling is a pain. Devtools takes a millennia to open, etc. I'm paranoid it could be due to the intricacy of the model, but it shouldn't be too bad in terms of that. Also, it appears without color, for some reason. Any help would be greatly appreciated!
import { component$, useOnDocument, $ } from '@builder.io/qwik';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export const Robot = component$(() => {
useOnDocument('qinit', $(() => {
let camera: THREE.PerspectiveCamera;
let scene: THREE.Scene;
let renderer: THREE.WebGLRenderer | null = null;
let frameId: number | null = null;
function init() {
const width = window.innerWidth;
const height = window.innerHeight;
try {
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.setClearColor(new THREE.Color('rgb(198,215,244)'), 0.5);
document.body.appendChild(renderer.domElement);
// Scene
scene = new THREE.Scene();
// Light Source
const light = new THREE.PointLight(new THREE.Color('rgb(232,227,92)'), 3, 100);
light.position.set(5, 5, 0);
scene.add(light);
// Camera
camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
camera.position.set(5, 5, 5);
camera.lookAt(0, 0, 0);
// Load asset
const loader = new GLTFLoader();
loader.load(
'/bane10-20.gltf',
(gltf) => {
scene.add(gltf.scene);
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
},
(error) => {
console.error('An error occurred while loading the GLTF model:', error);
}
);
animate();
} catch (error) {
console.error('An error occurred during initialization:', error);
}
}
function animate() {
if (!renderer) return;
frameId = requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function onResize() {
if (!renderer || !camera) return;
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener('resize', onResize);
init();
return () => {
if (frameId) cancelAnimationFrame(frameId);
if (renderer) {
renderer.dispose();
document.body.removeChild(renderer.domElement);
}
window.removeEventListener('resize', onResize);
};
}));
return <div></div>;
});
Upvotes: 0
Views: 38