「这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战」
雾
- 雾通常是基于离摄像机的距离褪色至某种特定颜色的方式。
- 在
three.js
中有两种设置雾的对象:
.Fog()
定义了线性雾。简单来说就是雾的密度是随着距离线性增大的。.FogExp2()
定义了指数雾。在相机附近提供清晰的视野,且距离相机越远,雾的浓度随着指数增长越快。
基础模版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>学习</title>
</head>
<body>
<canvas id="c2d" class="c2d" width="1000" height="500"></canvas>
<script type="module">
import * as THREE from 'https://threejs.org/build/three.module.js'
import { OrbitControls } from 'https://threejsfundamentals.org/threejs/resources/threejs/r132/examples/jsm/controls/OrbitControls.js'
const canvas = document.querySelector('#c2d')
// 渲染器
const renderer = new THREE.WebGLRenderer({ canvas })
const fov = 75 // 视野范围
const aspect = 2 // 相机默认值 画布的宽高比
const near = 0.1 // 近平面
const far = 10 // 远平面
// 透视投影相机
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far)
camera.position.set(0, 0, 10)
camera.lookAt(0, 0, 0)
// 控制相机
const controls = new OrbitControls(camera, canvas)
controls.update()
// 场景
const scene = new THREE.Scene()
// 渲染
function render(time) {
time *= 0.001
const rot = time
cube.rotation.x = rot
cube.rotation.y = rot
renderer.render(scene, camera)
requestAnimationFrame(render)
}
requestAnimationFrame(render)
</script>
</body>
</html>
Fog
属性
.name
对象的名称。.color
雾的颜色。.near
应用雾的最小距离。任何物体比near
近不会受到影响。.far
应用雾的最大距离。任何物体比far
远则完全是雾的颜色。
- 需要注意雾是作用在渲染的物体上的,想要实现效果就需要设定雾 和 场景的背景颜色为同一种颜色。
- 雾设置的最小距离,最大距离都是以相机所在位置计算的。
{
const near = 1
const far = 11
const color = 'lightblue'
scene.fog = new THREE.Fog(color, near, far)
scene.background = new THREE.Color(color)
}
{
const color = 0xffffff
const intensity = 1
const light = new THREE.DirectionalLight(color, intensity)
light.position.set(-1, 2, 4)
scene.add(light)
}
const box = 3
const geometry = new THREE.BoxGeometry(box, box, box)
const material = new THREE.MeshPhongMaterial({ color: 0x8844aa })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
fog
在材质上有个布尔属性,用来设置材质是否会受到雾的影响。默认是true
material.fog = false
FogExp2
属性
.name
对象的名称。.color
雾的颜色。.density
定义雾的密度将会增长多块。
- 使用方式和
Fog
一样,它效果更接近真实环境。
{
const color = 'lightblue'
const density = 0.1
scene.fog = new THREE.FogExp2(color, density)
scene.background = new THREE.Color(color)
}
总结
在开发中使用更多的是Fog
,因为它可以设定影响区域,你可以设定一定距离内显示清晰的场景,过了这段距离开始产生雾的效果。还要灵活的使用材质上的fog
属性,比如在房间里设置窗外是雾,不设置fog
属性在房间内的物体也会出现雾的效果。