Getting this issue, Actually iam trying to upload a 3d file and wanted to see in angular app.
Code :
import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
import { Engine, SceneLoader, Scene } from '@babylonjs/core';
import * as BABYLON from '@babylonjs/core';
import '@babylonjs/loaders';
import '@babylonjs/loaders/glTF'; // Import the glTF loader
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
@ViewChild('renderCanvas', { static: true }) renderCanvas!: ElementRef<HTMLCanvasElement>;
private engine!: BABYLON.Engine;
private scene!: BABYLON.Scene;
ngOnInit() {
this.engine = new BABYLON.Engine(this.renderCanvas.nativeElement, true);
this.createScene();
this.engine.runRenderLoop(() => {
if (this.scene) {
this.scene.render();
}
});
window.addEventListener('resize', () => {
this.engine.resize();
});
}
onFileSelected(event: any) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result as ArrayBuffer;
this.loadModel(arrayBuffer, file.name);
};
reader.readAsArrayBuffer(file);
}
}
private createScene() {
this.scene = new BABYLON.Scene(this.engine);
const camera = new BABYLON.ArcRotateCamera('camera', Math.PI / 2, Math.PI / 2, 10, BABYLON.Vector3.Zero(), this.scene);
camera.attachControl(this.renderCanvas.nativeElement, true);
const light = new BABYLON.HemisphericLight('light', new BABYLON.Vector3(1, 1, 0), this.scene);
this.scene.clearColor = new BABYLON.Color4(0, 0, 0, 1);
}
private loadModel(arrayBuffer: ArrayBuffer, fileName: string) {
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
// Determine the file extension
const extension = this.getFileExtension(fileName);
if (extension !== 'glb' && extension !== 'gltf') {
console.error('Unsupported file format:', extension);
URL.revokeObjectURL(url);
return;
}
// Clear the scene before loading the new model
if (this.scene) {
this.scene.dispose();
this.createScene();
} else {
console.error('Scene is not initialized');
URL.revokeObjectURL(url);
return;
}
// Debugging: Log the blob URL
console.log('Blob URL:', url);
// Load the model using the GLTF loader
SceneLoader.Append(url, '', this.scene, (_scene) => {
console.log('Model loaded');
URL.revokeObjectURL(url); // Clean up the URL after loading
}, null, (_scene, message, exception) => {
console.error('Error loading model:', message, exception);
URL.revokeObjectURL(url); // Clean up the URL in case of error
});
}
private getFileExtension(fileName: string): string {
return fileName.split('.').pop()?.toLowerCase() || '';
}
}
`> Blockquote
`