feat: implement declarative texture mapping in R3F

This commit is contained in:
divyap 2026-03-30 14:21:43 +05:30
parent 2a39171446
commit 9b6dc498a6
6 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Task 2 — Texture Mapping (R3F)</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

View File

@ -0,0 +1,21 @@
{
"name": "task-2-r3f",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@react-three/fiber": "^8.16.8",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"three": "^0.163.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.1",
"vite": "^5.0.0"
}
}

View File

@ -0,0 +1,17 @@
import { Canvas } from '@react-three/fiber'
import Box from './Box'
function App() {
return (
<div style={{ width: '100vw', height: '100vh', background: 'pink' }}>
<Canvas
camera={{ position: [0, 0, 5], fov: 75 }}
style={{ background: 'pink' }}
>
<Box />
</Canvas>
</div>
)
}
export default App

View File

@ -0,0 +1,38 @@
import { useRef, useMemo } from 'react'
import { useFrame } from '@react-three/fiber'
import * as THREE from 'three'
function Box() {
const meshRef = useRef()
const texture = useMemo(() => {
const canvas = document.createElement('canvas')
canvas.width = 256
canvas.height = 256
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, 256, 256)
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, 128, 128)
ctx.fillRect(128, 128, 128, 128)
return new THREE.CanvasTexture(canvas)
}, [])
useFrame(() => {
meshRef.current.rotation.x += 0.01
meshRef.current.rotation.y += 0.01
})
return (
<mesh ref={meshRef}>
<boxGeometry args={[2, 2, 2]} />
<meshBasicMaterial map={texture} />
</mesh>
)
}
export default Box

View File

@ -0,0 +1,4 @@
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(<App />)

View File

@ -0,0 +1,6 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})