添加好 场景 相机 渲染器
添加光 物体和平面:
最后渲染:
添加阴影的步骤:开通相应的true:
完整代码:
<script setup>
// 导入 threejs
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
// 创建场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb); // 浅蓝色
// 创建相机
const camera = new THREE.PerspectiveCamera(
45, // 视角
window.innerWidth / window.innerHeight,
0.1, // 近平面
1000 // 远平面
);
// 设置相机位置 我的视角
camera.position.z = 5;
camera.position.x = 2;
camera.position.y = 10;
camera.lookAt(0, 0, 0);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;//阴影1
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加坐标辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();
// 添加环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // 白色环境光,强度为0.5
scene.add(ambientLight);
// 添加平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1); // 白色平行光,强度为1
directionalLight.castShadow = true;//阴影2
directionalLight.position.set(5, 10, 7.5); // 设置光源位置
scene.add(directionalLight);
// 球体
const sphereGeometry = new THREE.SphereGeometry(1, 20, 20);
const material = new THREE.MeshStandardMaterial({ color: 0x808080 }); // 灰色
const sphere = new THREE.Mesh(sphereGeometry, material);
sphere.castShadow = true;//阴影3
scene.add(sphere);
// 创建平面
const planeGeometry = new THREE.PlaneGeometry(10, 10)
const plane = new THREE.Mesh(planeGeometry, material);
plane.position.set(0,-1,0);
plane.rotation.x = -Math.PI / 2;
plane.receiveShadow = true;//阴影4
scene.add(plane)
// 渲染函数
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
</script>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
display: block;
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
}
</style>