fix: rewrite texture loading logic
This commit is contained in:
+9
-29
@@ -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();
|
if (texture) {
|
||||||
loader.load(
|
texture.wrapS = THREE.RepeatWrapping;
|
||||||
'/img/niko.jpg',
|
texture.wrapT = THREE.RepeatWrapping;
|
||||||
(loadedTex) => {
|
texture.repeat.set(1, 1);
|
||||||
loadedTex.wrapS = THREE.RepeatWrapping;
|
}
|
||||||
loadedTex.wrapT = THREE.RepeatWrapping;
|
}, [texture]);
|
||||||
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();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
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>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user