Basically, a loaded model is nothing more than, for example, a regular image. It needs a frame — either with a fixed size or one that adapts to the screen.
Optionally, a loading indicator can be added, as loading usually takes a few seconds.
To enhance the first impression, the model should appear with a bit of an effect, so the user notices they can rotate, move, and zoom the model using a mouse or touch gestures.
An ideal library for this kind of task is THREE.JS, which is perfectly suited for even the most realistic renderings. To keep things as simple as possible, I bundled all the functionality into a module called ‘jo3dview.js’. You just need to include one additional CSS file: ‘jo3dview.css’, and you’re good to go.
The easiest way to use THREE.JS is via a CDN, so you don’t need to install anything. Of course, you can also install THREE.JS locally. THREE.JS is imported flexibly via an import map.
That’s all there is to it.
Now, you only need one or more models. Most 3D programs allow export to GLTF or GLB (GLB is simply a compressed GLTF format). You’ll also need a frame (a simple <DIV>) and a call to the loading function for rendering.
Embedding jo3dview
As mentioned earlier, insert the following into the <HEAD> of your HTML page:
<link rel="stylesheet" href="./jo3dview.css">
<script type="importmap">
{ "imports": { "three": "https://unpkg.com/three@latest/build/three.module.js", "three/addons/": "https://unpkg.com/three@latest/examples/jsm/" } }
</script>
<script type="module" defer src="./jo3dview.js"></script>
Then it’s enough to leave a frame in the appropriate place, for example like this, where the frame adjusts to the window size:
<div id="mviewer" class="jo3dviewer" style="width: 90vw; height: 80vh;">
<div id="mloader" class="jo3dloader"></div>
</div>
The inner element mloader is optional. To display the model, you just need to call the function:
view3d('mviewer', './rak3172sip.glb', 1.2, 'mloader');
A GitHub repository with a live demo can be found here:
Hint: For local testing, the best choice is the VS Code editor with the ‘Live Server’ plugin by Ritwick Dey.
Discussione (0 nota(e))