<template>
<div id="webgl"></div>
</template>
<script setup>
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const scene = new THREE.Scene();
// 目标:灯光与阴影
// 1、材质要满足能够对光照有反应
// 2、设置渲染器开启阴影的计算 renderer.shadowMap.enabled = true
// 3、设置光照投射阴影 directionalLight.castShadow = true
// 4、设置物体投射阴影 sphere.castShadow = true
// 5、设置物体接收阴影 plane.receiveShadow = true
const sphereGemometry = new THREE.SphereGeometry(1, 20, 20) // 球体
const material = new THREE.MeshStandardMaterial()
const sphere = new THREE.Mesh(sphereGemometry, material)
sphere.castShadow = true
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
scene.add(plane)
// 灯光
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.9)
directionalLight.position.set(5, 5, 5)
directionalLight.castShadow = true
scene.add(directionalLight)
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 10);
// scene.add(camera);
const axesHelper = new THREE.AxesHelper(5); // 长度
scene.add(axesHelper);
// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight); //设置three.js渲染区域的尺寸(像素px)
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
// 相机围绕目标进行轨道运动
const controls = new OrbitControls(camera, renderer.domElement);
function render(time) {
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render()
</script>
three.js光照与阴影
2024-05-14 08:38:10 27 阅读