fix: rewrite texture loading logic

This commit is contained in:
2025-12-28 18:04:31 -03:00
parent dda0dafbd7
commit 4ea26cb60c
+7 -27
View File
@@ -1,16 +1,15 @@
'use client'; 'use client';
import { Canvas, useFrame } from "@react-three/fiber"; import { Canvas, useFrame, useLoader } from "@react-three/fiber";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { OrbitControls } from '@react-three/drei'; import { OrbitControls } from '@react-three/drei';
import * as THREE from 'three'; import * as THREE from 'three';
function Cube() { function Cube() {
const meshRef = useRef<THREE.Mesh>(null); const meshRef = useRef<THREE.Mesh>(null);
const [texture, setTexture] = useState<THREE.Texture | null>(null); const texture = useLoader(THREE.TextureLoader, '/img/niko.jpg');
useFrame((state, delta) => { useFrame((state, delta) => {
if (meshRef.current) { if (meshRef.current) {
@@ -20,36 +19,17 @@ function Cube() {
}); });
useEffect(() => { useEffect(() => {
const loader = new THREE.TextureLoader();
loader.load(
'/img/niko.jpg',
(loadedTex) => {
loadedTex.wrapS = THREE.RepeatWrapping;
loadedTex.wrapT = THREE.RepeatWrapping;
loadedTex.repeat.set(1, 1);
setTexture(loadedTex);
},
undefined, // onProgress callback (optional)
(error) => {
console.error('Error loading texture:', error);
}
);
// Cleanup texture on unmount
return () => {
if (texture) { if (texture) {
texture.dispose(); texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);
} }
}; }, [texture]);
}, []);
return ( return (
<mesh ref={meshRef} castShadow receiveShadow> <mesh ref={meshRef} castShadow receiveShadow>
<boxGeometry args={[2.5, 2.5, 2.5]} /> <boxGeometry args={[2.5, 2.5, 2.5]} />
<meshBasicMaterial <meshBasicMaterial map={texture} />
map={texture}
color={texture ? undefined : '#1f1f1f'}
/>
</mesh> </mesh>
) )
} }