帮我写一个react three 的小案例
时间: 2024-04-10 18:26:43 浏览: 24
当然可以!下面是一个简单的 React + Three.js 的案例,展示了如何在 React 中创建一个简单的立方体场景:
1. 首先,确保你的项目已经安装了 React 和 Three.js 模块(可以参考上面的步骤)。
2. 创建一个新的 React 组件(例如 CubeScene.js),并添加以下代码:
```jsx
import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
const CubeScene = () => {
const canvasRef = useRef(null);
useEffect(() => {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: canvasRef.current });
renderer.setSize(window.innerWidth, window.innerHeight);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}, []);
return <canvas ref={canvasRef} />;
};
export default CubeScene;
```
3. 在你的主组件或页面中导入并渲染 `CubeScene` 组件:
```jsx
import React from 'react';
import CubeScene from './CubeScene';
const App = () => {
return (
<div>
<h1>React + Three.js Cube Scene</h1>
<CubeScene />
</div>
);
};
export default App;
```
4. 运行你的 React 应用程序,你应该能够在页面上看到一个旋转的立方体场景。
这只是一个简单的示例,你可以根据需要对场景进行更多的自定义和扩展。希望这可以帮助到你开始使用 React 和 Three.js 创建有趣的三维场景!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)