threejs基本知识4 (基本常用灯光及阴影)
AmbientLight / 基础环境光,DirectionalLight / 类太阳光,PointLight / 点光源(发散),SpotLight / 点光源(凝聚),DirectionalLightHelper / 光源辅助器;
展现阴影四要素:1、场景开启阴影渲染 renderer.shadowMap.enabled = true(加载场景和相机之前,否者不显示阴影);2、投射灯光要开启阴影效果 dLight.castShadow = true;3、阴影要有产生者 sphere.castShadow = true;4、阴影要有投射面板(阴影显示区域)plane.receiveShadow = true;
// 基础环境光(颜色 / 强度)
const light = new THREE.AmbientLight("#ffffff", 0.2);
// 方向光(平行光)
const dLight = new THREE.DirectionalLight("#fff", 0.8);
// 方向光辅助器
const dlHelper = new THREE.DirectionalLightHelper(dLight);
dLight.position.set(0, 1.3, 1);
dLight.lookAt(0, 0, 2);
// 灯光开启阴影效果
dLight.castShadow = true;
// 阴影模糊度(2的次方 512 / 1024 / 2048 默认为512 )
dLight.shadow.mapSize.width = 2048;
dLight.shadow.mapSize.height = 2048;
// 点光源(发散光)
// const pointLight = new THREE.PointLight("red", 0.8);
// pointLight.position.set(0, 1, 1);
// pointLight.lookAt(0, 0, 2);
// 点光源辅助器
// const plHelper = new THREE.PointLightHelper(pointLight);
// 点光源(凝聚光)
// const spotLight = new THREE.SpotLight('orange',0.8)
// spotLight.position.set(0, 1, 1);
// spotLight.lookAt(0, 0, 2);
// 点光源辅助器
// const splHelper = new THREE.SpotLightHelper(spotLight)
// 高光材质 比兰伯特材质多了高光效果 需要光源才可见
const material = new THREE.MeshPhongMaterial({
color: "red",
shininess: 50, // 闪亮程度 默认是30 如果设置为0 则等同于兰伯特材质
});
// 球体
const sphereGeometry = new THREE.SphereGeometry(0.3);
const sphere = new THREE.Mesh(sphereGeometry, material);
sphere.position.y = 0.5;
sphere.castShadow = true; // 阴影产生者
// 平面
const planeGeometry = new THREE.PlaneGeometry(6, 6);
const plane = new THREE.Mesh(
planeGeometry,
new THREE.MeshPhongMaterial()
);
plane.position.y = 0;
plane.rotation.x = -(90 / 180) * Math.PI; // 45°
plane.receiveShadow = true; // 阴影投射位置(接收阴影的面板墙)
// 立方体
const boxGeometry = new THREE.BoxGeometry(0.4, 0.4, 0.4);
const cube = new THREE.Mesh(boxGeometry, material);
cube.position.set(0.8, 0.5, 0);
scene.add(sphere);
scene.add(plane);
scene.add(cube);
// scene.add(light);
// scene.add(dLight);
// scene.add(dlHelper);
// scene.add(pointLight);
// scene.add(plHelper);
// scene.add(spotLight)
// scene.add(splHelper)
scene.add(axes);
const renderer = new THREE.WebGLRenderer(); // 创建渲染器
renderer.setSize(w, h); // 渲染器尺寸
renderer.shadowMap.enabled = true; // 场景开启阴影渲染
renderer.render(scene, camera); // 场景和相机放在渲染器中