import React, { useRef, useEffect } from 'react';
import * as THREE from 'three';
const SimpleScene = () => {
const containerRef = useRef();
useEffect(() => {
let scene, camera, renderer, cube;
// 创建场景
scene = new THREE.Scene();
// 创建相机
camera = new THREE.PerspectiveCamera(75, containerRef.current.clientWidth / containerRef.current.clientHeight, 0.1, 1000);
camera.position.z = 5;
// 创建渲染器
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(containerRef.current.clientWidth, containerRef.current.clientHeight);
containerRef.current.appendChild(renderer.domElement);
// 创建立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 渲染场景
const animate = () => {
requestAnimationFrame(animate);
// 使立方体旋转起来
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
return () => {
// 在组件卸载时执行清理操作
renderer.domElement.remove();
};
}, []);
return <div ref={containerRef} style={{ width: '100%', height: '400px' }} />;
};
export default SimpleScene;
react中创建一个简单的three.js应用
最新推荐文章于 2024-04-22 08:49:29 发布