步骤:
- 材质能够对光照的反应
- 设置渲染器开启阴影的计算: renderer.shadowMap.enabled = true
- 设置光照投射阴影: directionalLight.castShadow = true
- 设置物体投射阴影: sphere.castShadow = true
- 设置物体接受阴影: plane.receiveShadow = true;
- 设置投影的分辨率 directionalLight.shadow.mapSize.set(2048,2048)
- 设置阴影弧度 directionalLight.shadow.radius = 20
<!-- 阴影基础 -->
<template>
<div></div>
</template>
<script>
/* eslint-disable */
import * as THREE from 'three';
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls.js"
let scene; // 场景
let camera; // 相机
let renderer; // 渲染器
let controls; // 轨道控制器
let cube ; // 几何体
export default {
name:"component06-01",
data () {
return {
};
},
components:{},
computed:{},
mounted(){
this.init()
this.render()
},
methods:{
init(){
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
)
// 相机位置
camera.position.set(0,0,10);
scene.add(camera)
// 初始化渲染器
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
renderer.shadowMap.enabled = true; // 开启渲染器阴影的计算
document.body.appendChild(renderer.domElement)
// 创建坐标辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add( axesHelper );
// 初始化轨道器
controls = new OrbitControls(camera,renderer.domElement)
// 全景光线
const light = new THREE.AmbientLight("#ffffff")
scene.add(light)
// 直线光线
const directionalLight = new THREE.DirectionalLight("#ffffff")
directionalLight.position.set(10,10,10)
directionalLight.castShadow = true // 光照投射阴影
directionalLight.shadow.mapSize.set(2048,2048) // 阴影的分辨率
directionalLight.shadow.radius = 20;
scene.add(directionalLight)
// RGBE渲染器
const material = new THREE.MeshStandardMaterial({
metalness:0.7,
roughness:0.1,
})
// 创建球体
const sphereGeometry = new THREE.SphereGeometry( 1,200,200 );
const sphere = new THREE.Mesh(sphereGeometry,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.receiveShadow = true; // 设置物体接受阴影
plane.rotation.x = -Math.PI / 2
scene.add(plane)
},
render(){
renderer.render(scene,camera)
controls.update();
requestAnimationFrame(this.render)
}
}
}
</script>
<style scoped>
</style>
2. 平行光投影相机属性参数
directionalLight.shoadow.camera.near = 0.5
directionalLight.shoadow.camera.far = 500
directionalLight.shoadow.camera.top = 5
directionalLight.shoadow.camera.bottom = -*5
directionalLight.shoadow.camera.left = -5
directionalLight.shoadow.camera.right = 5