jak mam spustit tento skript import { useState, useEffect } from 'react'; import {…
- User
jak mam spustit tento skript
import { useState, useEffect } from 'react'; import { Canvas, useThree } from '@react-three/fiber'; import { OrbitControls, Line, Text } from '@react-three/drei'; import * as THREE from 'three';
const Circle3D = ({ plane, color, numPoints, rotationAngle }) => { const points = []; for (let i = 0; i <= 64; i++) { const angle = (i / 64) * Math.PI * 2; const x = Math.cos(angle); const y = Math.sin(angle); switch (plane) { case 'XY': points.push(new THREE.Vector3(x, y, 0)); break; case 'YZ': points.push(new THREE.Vector3(0, x, y)); break; case 'XZ': points.push(new THREE.Vector3(x, 0, y)); break; } }
return ( <group rotation={[ plane === 'YZ' ? rotationAngle : 0, plane === 'XZ' ? rotationAngle : 0, plane === 'XY' ? rotationAngle : 0 ]}> {Array.from({ length: numPoints }).map((_, index) => { const angle = (index / numPoints) * Math.PI * 2; const x = Math.cos(angle); const y = Math.sin(angle); let position; switch (plane) { case 'XY': position = [x, y, 0]; break; case 'YZ': position = [0, x, y]; break; case 'XZ': position = [x, 0, y]; break; } return ( <sphereGeometry args={[0.03, 16, 16]} /> <Text position={[position[0] * 1.1, position[1] * 1.1, position[2] * 1.1]} fontSize={0.1} color={color} anchorX="center" anchorY="middle" > {index + 1} ); })} ); };
const Scene = ({ circles, lines, triangles, fillTriangles }) => { const { scene } = useThree(); useEffect(() => { scene.background = new THREE.Color(0x111111); }, [scene]);
const getPointOnCircle = (plane, index, totalPoints, rotationAngle) => { const angle = (index / totalPoints) * Math.PI * 2 + rotationAngle; const x = Math.cos(angle); const y = Math.sin(angle); switch (plane) { case 'XY': return new THREE.Vector3(x, y, 0); case 'YZ': return new THREE.Vector3(0, x, y); case 'XZ': return new THREE.Vector3(x, 0, y); default: return new THREE.Vector3(0, 0, 0); } };
return ( <> <pointLight position={[10, 10, 10]} intensity={1} /> <pointLight position={[-10, -10, -10]} intensity={0.5} /> {circles.map((circle, index) => ( ))} {lines.map((line, index) => { const point1 = getPointOnCircle(circles[line[0].circle].plane, line[0].point, circles[line[0].circle].numPoints, circles[line[0].circle].rotationAngle); const point2 = getPointOnCircle(circles[line[1].circle].plane, line[1].point, circles[line[1].circle].numPoints, circles[line[1].circle].rotationAngle); return <Line key={index} points={[point1, point2]} color="#00FFFF" lineWidth={8} />; })} {triangles.map((triangle, index) => { const points = triangle.map(t => getPointOnCircle(circles[t.circle].plane, t.point, circles[t.circle].numPoints, circles[t.circle].rotationAngle)); return ( <bufferAttribute attach="attributes-position" array={new Float32Array(points.flatMap(v => [v.x, v.y, v.z]))} itemSize={3} count={3} /> <meshPhongMaterial color="#FFFF00" side={THREE.DoubleSide} transparent opacity={fillTriangles ? 0.7 : 0} /> <Line points={[...points, points[0]]} color="#FF00FF" lineWidth={4} /> ); })} </> ); };
const Home = () => { const [numPoints, setNumPoints] = useState(12); const [selectedPoints, setSelectedPoints] = useState([0, 0, 0]); const [circles, setCircles] = useState([]); const [lines, setLines] = useState([]); const [triangles, setTriangles] = useState([]); const [fillTriangles, setFillTriangles] = useState(false);
useEffect(() => { const newCircles = [ { plane: 'XY', color: '#FF4136', numPoints, rotationAngle: 0 }, { plane: 'YZ', color: '#2ECC40', numPoints, rotationAngle: 0 }, { plane: 'XZ', color: '#0074D9', numPoints, rotationAngle: 0 }, ]; setCircles(newCircles); }, [numPoints]);
const handlePointSelection = (circleIndex, point) => { const newSelectedPoints = [...selectedPoints]; newSelectedPoints[circleIndex] = point; setSelectedPoints(newSelectedPoints); };
const handleDraw = () => { const nonZeroPoints = selectedPoints.filter(point => point !== 0); const zeroCount = selectedPoints.filter(point => point === 0).length;
if (zeroCount === 0 && nonZeroPoints.length === 3) { // Draw triangle setTriangles(prevTriangles => [...prevTriangles, [ { circle: 0, point: selectedPoints[0] - 1 }, { circle: 1, point: selectedPoints[1] - 1 }, { circle: 2, point: selectedPoints[2] - 1 } ]]); } else if (zeroCount === 1 && nonZeroPoints.length === 2) { // Draw line const [index1, index2] = selectedPoints.map((point, index) => point !== 0 ? index : -1).filter(index => index !== -1); setLines(prevLines => [...prevLines, [ { circle: index1, point: selectedPoints[index1] - 1 }, { circle: index2, point: selectedPoints[index2] - 1 } ]]); } // If zeroCount is 2 or 3, do nothing (don't draw) setSelectedPoints([0, 0, 0]);};
const handleRotateCircle = (circleIndex) => { const newCircles = [...circles]; newCircles[circleIndex].rotationAngle += Math.PI / numPoints; setCircles(newCircles); };
return ( Number of Points: <input id="numPoints" type="number" value={numPoints} onChange={(e) => setNumPoints(Math.max(3, parseInt(e.target.value)))} className="w-full p-2 mb-4 text-sm text-gray-300 bg-gray-700 border border-gray-600 rounded-lg focus:ring-blue-500 focus:border-blue-500" /> {[0, 1, 2].map((index) => ( <button onClick={() => handlePointSelection(index, (selectedPoints[index] + 1) % (numPoints + 1))} className="w-full p-2 text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500" > Circle {index + 1}: {selectedPoints[index]} ))} Draw <button onClick={() => setFillTriangles(!fillTriangles)} className="w-full p-2 text-white bg-purple-600 rounded-lg hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500" > {fillTriangles ? 'Wireframe' : 'Fill'} Triangles <Canvas camera={{ position: [3, 3, 3] }}> {[0, 1, 2].map((index) => ( <button key={index} onClick={() => handleRotateCircle(index)} className="w-full p-2 mb-2 text-white bg-yellow-600 rounded-lg hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500" > Rotate Circle {index + 1} ))} ); };
export default Home;
- Assistant
Ahoj! Rád ti pomohu spustit tento React skript, který využívá React Three Fiber pro 3D vizualizaci. Níže jsou krok za krokem instrukce, jak nastavit a spustit tento projekt.
1. Předpoklady
Ujisti se, že máš nainstalovaný Node.js a npm (Node Package Manager). Pokud je nemáš, stáhni a nainstaluj je z nodejs.org.
2. Vytvoření nového React projektu
Nejjednodušší způsob, jak začít, je pomocí Create React App. Otevři terminál a spusť následující příkaz:
npx create-react-app my-3d-app cd my-3d-app3. Instalace potřebných závislostí
Projekt vyžaduje několik knihoven:
- three: JavaScriptová knihovna pro 3D grafiku.
- @react-three/fiber: React renderer pro Three.js.
- @react-three/drei: Knihovna užitečných komponent pro React Three Fiber.
- tailwindcss (volitelné): Pokud chceš používat styly jako ve tvém skriptu.
Instalace Three.js a React Three Fiber
V terminálu spusť:
npm install three @react-three/fiber @react-three/drei(Volitelně) Instalace Tailwind CSS
Pokud chceš použít Tailwind CSS pro styly, postupuj podle následujících kroků. Pokud ne, můžeš buď odstranit třídy (např.
className="flex h-screen bg-gray-900") nebo použít vlastní styly.a. Instalace Tailwind CSS
Postup podle oficiální dokumentace Tailwind CSS pro Create React App:
npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -pb. Konfigurace Tailwind
Otevři soubor
tailwind.config.jsa nastav cestu k šablonám:/** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./src/**/*.{js,jsx,ts,tsx}", ], theme: { extend: {}, }, plugins: [], }c. Přidání Tailwind do CSS
Otevři
src/index.cssa přidej následující řádky:@tailwind base; @tailwind components; @tailwind utilities;4. Přidání poskytnutého skriptu
a. Vytvoření komponenty
HomeVytvoř nový soubor
src/Home.jsa vlož do něj tvůj skript:import React, { useState, useEffect } from 'react'; import { Canvas, useThree } from '@react-three/fiber'; import { OrbitControls, Line, Text } from '@react-three/drei'; import * as THREE from 'three'; // [Vlož celý tvůj poskytnutý kód zde, začínající od `const Circle3D = ({ plane, color, numPoints, rotationAngle }) => {` a končící `export default Home;`]b. Aktualizace
App.jsOtevři
src/App.jsa nahraď jeho obsah následujícím kódem, který importuje a zobrazuje komponentuHome:import React from 'react'; import Home from './Home'; import './index.css'; // Ujisti se, že Tailwind CSS je importován function App() { return ( <Home /> ); } export default App;5. Spuštění projektu
V terminálu, ve složce projektu (
my-3d-app), spusť:npm startTím se spustí vývojový server a otevře se ti tvůj projekt v prohlížeči na adrese http://localhost:3000.
6. Oprava případných problémů
a. Kontrola stylů
Pokud používáš Tailwind CSS, ujisti se, že všechny styly fungují správně. Pokud Tailwind není nezbytný, můžeš odstranit třídy
classNamez JSX a aplikovat vlastní CSS styly podle potřeby.b. Kontrola verzí knihoven
Ujisti se, že máš kompatibilní verze knihoven. Někdy mohou nové verze knihoven mít breaking changes. Pokud se setkáš s chybami, zkontroluj dokumentaci knihoven nebo vyzkoušej starší verze.
c. Kontrola konzole pro chyby
Pokud aplikace nefunguje dle očekávání, otevři si konzoli v prohlížeči (F12 nebo pravý klik → "Inspect") a podívej se na případné chybové zprávy, které ti mohou pomoci identifikovat problém.
7. Další kroky
- Styling: Pokud nejsi obeznámen s Tailwind CSS, doporučuji se podívat na oficiální dokumentaci nebo upravit styly podle svých potřeb.
- Rozšíření aplikace: Můžeš přidat další funkce nebo vylepšit stávající podle svých požadavků.
Pokud budeš mít další otázky nebo narazíš na problémy, neváhej se ozvat!