3.js 真tm枯燥啊,狗都不学
效果图
源码
// @ts-nocheck
// 引入three.js
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'
// 导入tween
import * as TWEEN from 'three/examples/jsm/libs/tween.module.js'
// 导入hdr加载器
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'
// 导入gltf加载器
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
// 导入draco解码器
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
//#region
const scence = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(2, 2, 5) // 设置相机位置
camera.lookAt(0, 0, 0)
const renderer = new THREE.WebGLRenderer({
antialias: true // 开启抗锯齿
})
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
//#endregion
//#region
// 添加世界坐标辅助器,红色-X轴; 绿色-Y轴; 蓝色-Z轴
const axesHelper = new THREE.AxesHelper(5)
scence.add(axesHelper)
const controls = new OrbitControls(camera, renderer.domElement)
// 设置带阻尼的惯性
// controls.enableDamping = true
// 设置阻尼系数
controls.dampingFactor = 0.05
// 每一帧根据控制器更新画面
function animate() {
// 如果,需要控制器带有阻尼效果,或者自动旋转等效果,就需要加入`controls.update()`
controls.update()
// `requestAnimationFrame`:在屏幕渲染下一帧画面时,触发回调函数来执行画面的渲染
requestAnimationFrame(animate)
// 渲染
renderer.render(scence, camera)
// 更新tween
TWEEN.update()
}
animate()
//#endregion
// --------------------------------------------------------------
// --------------------------------------------------------------
let rgbeLoader = new RGBELoader()
rgbeLoader.load('../public/assets/texture/Alex_Hart-Nature_Lab_Bones_2k.hdr', envMap => {
envMap.mapping = THREE.EquirectangularRefractionMapping
scence.background = envMap
scence.environment = envMap
})
`模板渲染的步骤`
步骤1、2个物体,都设置模板缓冲区的写入和测试
步骤2、2个物体,都设置模板缓冲区的基准值(stencilRef: 2)
步骤3、在平面上,设置允许写入的掩码(0xff,即:0~255)
步骤4、在小球上,设置模板比较函数`THREE.EqualStencilFunc`(比较的是2个物体的基准值,相等的时候才渲染)
步骤5、在平面上,设置当前函数比较通过的时候,设置为replace替换(`THREE.ReplaceStencilOp`)
const plane = new THREE.PlaneGeometry(6, 6)
const planeMaterial = new THREE.MeshPhysicalMaterial({
stencilWrite: true, // 设置模板缓冲区
stencilRef: 2,
stencilWriteMask: 0xff,
stencilZPass: THREE.ReplaceStencilOp
})
const planeMesh = new THREE.Mesh(plane, planeMaterial)
scence.add(planeMesh)
const sphere = new THREE.SphereGeometry(1, 20, 20)
const sphereMaterial = new THREE.MeshPhysicalMaterial({
color: 0xffcccc,
stencilWrite: true, // 设置模板缓冲区
stencilRef: 2,
stencilFunc: THREE.EqualStencilFunc,
depthTest: false, // 关闭深度测试
})
const sphereMesh = new THREE.Mesh(sphere, sphereMaterial)
sphereMesh.position.z = 5
// sphereMesh.position.z = -10 // 为负数时候,小球就会被挡住,只需要将它的深度测试(depthTest: false)关闭,就能正常显示了
scence.add(sphereMesh)