0

Working on a react app which uses react-three-fiber to display OBJ files whenever a user selects a file component in the sidebar. The challenge is that whenever the user selects a file it is displayed along side the previously selected file. How do I clear the canvas before loading a new model?

Here is the code that displays the object in the canvas: When a file is clicked its URL is forwarded as a prop to <ThreeScene />

import "../../styles.css";
import * as THREE from "three";
import { Canvas } from "@react-three/fiber";
import { useLoader } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader";
import { DDSLoader } from "three-stdlib";
import { Suspense, useRef, useState } from "react";
import Loading from "../project/Loading";

THREE.DefaultLoadingManager.addHandler(/\.dds$/i, new DDSLoader());

const Scene = ({ url }) => {
  const meshRef = useRef();
  const [hovered, setHovered] = useState(false);

  const materials = useLoader(MTLLoader, "models/Poimandres.mtl");
  let obj = null;
  obj = useLoader(
    OBJLoader,
    url,
    (loader) => {
      materials.preload();
      loader.setMaterials(materials);
    }
  );

  return obj ? (
    <mesh
      ref={meshRef}
      onPointerDown={(e) => setHovered(true)}
      onPointerOut={(e) => setHovered(false)}
    >
      <ambientLight intensity={0.2} />
      <spotLight position={[100, 100, 100]} angle={0.15} penumbra={1} />
      <spotLight position={[-100, -100, -100]} angle={-0.15} penumbra={1} />
      <primitive object={obj} scale={0.002} />
      <meshPhysicalMaterial
        attach="material"
        color={hovered ? "red" : "gray"}
        wireframe
      />
    </mesh>
  ) : (
    <Loading message={"Loading model"} />
  );
};

export default function ThreeScene({ url }) {
  return (
   <Canvas>
    <Suspense fallback={null}>
      <Scene url={url} />
      <OrbitControls />
    </Suspense>
   </Canvas>
  );
}

Also when I open a dialog/modal above the canvas it opens very slowly. How do I improve the performance?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.