I am quite new to ThreeJS (so bear with me), and this part of Exporting is something, I am not familiar with. Hence I ChatGPTied, this part of code
I was expecting the code, to export the model after a time of 5 seconds. Which it exports, however, it is not attaching animations to it
Can anyone help me out please?
Thanks
import React, { useRef, useEffect, useState } from 'react';
import { Canvas, useFrame, useThree } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import * as THREE from 'three';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter';
import './App.css';
function Model({ onComplete }) {
const meshRef = useRef();
const { scene } = useThree();
const [mixer] = useState(() => new THREE.AnimationMixer());
const clock = new THREE.Clock();
const [exported, setExported] = useState(false);
useEffect(() => {
if (meshRef.current) {
// Define keyframes
const positionKF = new THREE.VectorKeyframeTrack(
'.position',
[0, 5], // times
[0, 0, 0, 1, 2, 3] // values
);
const scaleKF = new THREE.VectorKeyframeTrack(
'.scale',
[0, 5], // times
[1, 1, 1, 5, 5, 5] // values
);
const rotationKF = new THREE.QuaternionKeyframeTrack(
'.quaternion',
[0, 5], // times
[
0, 0, 0, 1,
...new THREE.Quaternion().setFromEuler(new THREE.Euler(Math.PI / 4, Math.PI / 4, Math.PI / 4)).toArray()
] // values
);
// Create animation clip
const clip = new THREE.AnimationClip('Action', -1, [positionKF, scaleKF, rotationKF]);
// Add the clip to the mixer
const action = mixer.clipAction(clip, meshRef.current);
action.play();
// Export the model after the animation is complete
setTimeout(() => {
if (!exported) {
handleExport(scene, clip);
setExported(true);
}
}, 5000); // 5 seconds for the animation to complete
}
}, [mixer, exported, scene]);
useFrame(() => {
const delta = clock.getDelta();
mixer.update(delta);
});
const handleExport = (scene, clip) => {
const exporter = new GLTFExporter();
const options = {
binary: true,
animations: [clip]
};
exporter.parse(
scene,
(result) => {
const blob = new Blob([result], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'animated_model.glb';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
(error) => {
console.error('An error occurred during parsing', error);
},
options
);
};
return (
<mesh ref={meshRef}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="gray" wireframe={false} />
</mesh>
);
}
// App component to set up the scene and export functionality
export default function App() {
return (
<>
<Canvas camera={{ position: [-8, 5, 8] }}>
<ambientLight intensity={0.5} />
<gridHelper />
<Model />
<OrbitControls />
</Canvas>
</>
);
}