Open FRC9149 opened 1 month ago
To use the provided JavaScript code for creating a 3D object with Three.js while ensuring that it can work seamlessly with a script element in your HTML, you can structure your code to make sure that the necessary libraries are loaded properly. Since you want to avoid using a script element in HTML for loading Three.js and its components, here's a way to organize your code to achieve this:
Use import to Load Libraries: You can keep using the import statements as you have. To use the code effectively in a browser environment, you'll typically need a local server to serve your files or use a module bundler like Webpack or Rollup. Here’s how you can structure your files and load the script properly.
Example HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Object Viewer</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="threejs-canvas"></canvas>
<script type="module">
import { create3dObject } from './path/to/your/module.js';
const canvas = document.getElementById('threejs-canvas');
const pathToObj = 'path/to/your/model'; // Update with your model path
create3dObject(canvas, pathToObj, window.innerWidth, window.innerHeight, true, [0, 1, 5]);
</script>
</body>
</html>
The create3dObject Function The function you provided should work fine as is. It creates a Three.js scene, loads a model, and adds it to the scene. Make sure your paths to the .obj and .mtl files are correct.
I must have confused you. There is a section of html script, that if removed, stops everything from working. I tried again with your code but it didn't work. I don't think there's a way around this as when digging through the console errors, it says that OBJLoader & MTLLoader are missing a ThreeJs dependency.
I've tried downloading it with npm as well but I didn't get that to work. This system does work however, so I'll probably spend 1 more night on it then leave it be.
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.168.0/build/three.module.js",
"addons": "https://cdn.jsdelivr.net/npm/three@0.168.0/examples/jsm/"
}
}
</script>
I think this is just the way you have to make it, which upsets me.
(I'm using live server on vscode for the local server)
Inorder for the library to work, you have to implement a script element in html. When envisioning this library I wanted it all in an import, but I don't know how to get around that yet.