在这里,我尝试在 React 项目中使用 Threejs 制作球体,它已成功编译,我在控制台中也没有收到任何错误,但在输出中我得到的只是黑色画布而不是球体,所以我任何人都可以提供帮助,这将是很棒的.
import React, { useRef, useEffect } from 'react';
// import './Three.css';
import * as THREE from 'three';
const Three = () => {
const canvasRef = useRef();
useEffect(() => {
// Scene
const scene = new THREE.Scene();
// Create a sphere shape
const geometry = new THREE.SphereGeometry(15, 64, 32);
const material = new THREE.MeshStandardMaterial({
color: "#00ff83",
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// Lights
const light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(0, 10, 10);
scene.add(light);
// Camera
const camera = new THREE.PerspectiveCamera(45, 800/600);
camera.position.z = 20;
scene.add(camera);
// Renererd
// const canvas = new document.querySelector('.webgl');
const renderer = new THREE.WebGLRenderer({canvas: canvasRef.current || undefined});
renderer.setSize(800, 600);
renderer.render(scene, camera)
}, []); // Empty dependency array ensures that this effect runs once when the component mounts
return (
<div>
<canvas ref={canvasRef} className='webgl'></canvas>
</div>
);
};
export default Three;
首先,你的球体是黑色的,因为场景中没有足够的光线,你的背景也是黑色的,所以你看不到球体。
添加:
const al = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(al);
其次,与画布相比,球体的半径太大了。
更改为:
const geometry = new THREE.SphereGeometry(5, 32, 32);
如果您想检查当前球体的大小及其半径,您可以先添加灯光并更改颜色,然后您会看到它会散布在整个画布上。
最后放置动画循环。
const animate = () => {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
正如上面那位同事提到的,如果你不想要 vanilla 3js,那么使用 R3F 会更更干净。