https://github.com/user-attachments/assets/1d60975e-7205-45ad-ae64-700c050778e0
This project demonstrates how to implement drag and drop functionality for GLTF/GLB models in a Threlte application. It shows how to load 3D models dynamically and replace them at runtime using the browser's drag and drop API.
npm install @threlte/core @threlte/extras three
The main functionality is implemented in Scene.svelte
:
import { T, useTask } from '@threlte/core';
import { interactivity, OrbitControls, useGltf } from '@threlte/extras';
import { Spring } from 'svelte/motion';
import { writable } from 'svelte/store';
Create a writable store to manage the current model URL:
const modelUrl = writable('path/to/initial/model.gltf');
Implement the drag and drop functionality:
function handleDrop(event: DragEvent) {
event.preventDefault();
const file = event.dataTransfer?.files[0];
if (file && (file.name.endsWith('.glb') || file.name.endsWith('.gltf'))) {
const url = URL.createObjectURL(file);
modelUrl.set(url);
}
}
Add the event listeners to your window:
<svelte:window on:dragover|preventDefault on:drop={handleDrop} />
Use Threlte's useGltf
hook to load the model:
{#await useGltf($modelUrl)}
<!-- Loading state -->
<T.Mesh>
<T.SphereGeometry args={[0.5, 16, 16]} />
<T.MeshStandardMaterial color="gray" wireframe />
</T.Mesh>
{:then gltf}
<T
is={gltf.scene}
rotation.y={rotation}
position.y={1}
scale={scale.current}
/>
{:catch error}
<!-- Error state -->
<T.Mesh>
<T.BoxGeometry args={[1, 1, 1]} />
<T.MeshStandardMaterial color="red" />
</T.Mesh>
{/await}
useGltf
from @threlte/extras
for efficient model loadingURL.createObjectURL()
to create local URLs for dropped files<T>
) instead of raw Three.js objects<T>
componentOrbitControls
for camera manipulationMIT