fix: rewrite texture loading logic
This commit is contained in:
+9
-29
@@ -1,16 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { Canvas, useFrame } from "@react-three/fiber";
|
||||
import { Canvas, useFrame, useLoader } from "@react-three/fiber";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { OrbitControls } from '@react-three/drei';
|
||||
|
||||
import * as THREE from 'three';
|
||||
|
||||
|
||||
function Cube() {
|
||||
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) => {
|
||||
if (meshRef.current) {
|
||||
@@ -20,36 +19,17 @@ function Cube() {
|
||||
});
|
||||
|
||||
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) {
|
||||
texture.dispose();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
if (texture) {
|
||||
texture.wrapS = THREE.RepeatWrapping;
|
||||
texture.wrapT = THREE.RepeatWrapping;
|
||||
texture.repeat.set(1, 1);
|
||||
}
|
||||
}, [texture]);
|
||||
|
||||
return (
|
||||
<mesh ref={meshRef} castShadow receiveShadow>
|
||||
<boxGeometry args={[2.5, 2.5, 2.5]} />
|
||||
<meshBasicMaterial
|
||||
map={texture}
|
||||
color={texture ? undefined : '#1f1f1f'}
|
||||
/>
|
||||
<meshBasicMaterial map={texture} />
|
||||
</mesh>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user