1、创建场景雾
//创建场景雾
scene.fog = new THREE.Fog(0x999999,0.1,50);
2、创建场景指数雾
scene.fog = new THREE.FogExp2(0x999999,0.05);
3、 设置场景背景颜色
scene.background = new THREE.Color(0x999999);
完整代码
<script setup>
// 导入threejs
import * as THREE from "three"
// 引入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 引入lil.gui
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js";
//导入hdr加载器
import{ RGBELoader} from "three/examples/jsm/loaders/RGBELoader.js"
// 创建场景
const scene = new THREE.Scene();
//创建相机
const camera = new THREE.PerspectiveCamera(
800,// 视角
window.innerWidth / window.innerHeight,
0.1, // 近平面
1000 // 远平面
);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
//设置相机位置
camera.position.x=5;
camera.position.y=5;
camera.position.z=5;
//相机默认看向远点
camera.lookAt(0,0,0);
// 添加世界坐标辅助器
const axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);
// 添加轨道控制器
const controls = new OrbitControls(camera,renderer.domElement);
// 设置带阻尼的惯性
controls.enableDamping=true;
// 设置阻尼系数
controls.dampingFactor = 0.05;
// 设置自动旋转
//controls.autoRotate = true;
//渲染函数
function animate(){
controls.update();
requestAnimationFrame(animate);
renderer.render(scene,camera);
}
animate();
// 监听窗口变化
window.addEventListener("resize",()=>{
camera.aspect = window.innerWidth / window.innerHeight;
// 更新摄像机的投影矩阵
camera.updateProjectionMatrix();
// 更新渲染器
renderer.setSize(window.innerWidth, window.innerHeight);
// 设置渲染器的像素比
renderer.setPixelRatio(window.devicePixelRatio);
})
// 创建GUI
const gui = new GUI();
// 创建长方体
const boxGeometry = new THREE.BoxGeometry(1,1,100);
// 创建长方体材质
const boxMaterial = new THREE.MeshBasicMaterial({
color:0x00ff00,
})
const box = new THREE.Mesh(boxGeometry,boxMaterial);
scene.add(box);
//创建场景雾
//scene.fog = new THREE.Fog(0x999999,0.1,50);
// 创建场景指数雾
scene.fog = new THREE.FogExp2(0x999999,0.05);
// 设置场景背景颜色
scene.background = new THREE.Color(0x999999);
</script>
<template>
<div></div>
</template>
<style >
*{
margin: 0;
padding: 0;
}
canvas{
display: block;
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
}
</style>
效果