效果图
如图所示,选中的黄色线框效果
引入库
import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'
import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass'
import { FXAAShader } from 'three/examples/jsm/shaders/FXAAShader'
添加效果合成器
function initEffectComposer() {
const parameters = { format: THREE.RGBFormat }
const size = renderer.getDrawingBufferSize(new THREE.Vector2())
const renderTarget = new THREE.WebGLMultisampleRenderTarget(size.width, size.height, parameters)
composeroutline = new EffectComposer(renderer, renderTarget)
renderSceneoutline = new RenderPass(scene, camera)
renderSceneoutline.clear = true
composeroutline.addPass(renderSceneoutline)
outlinePass = new OutlinePass(new THREE.Vector2(width, height), scene, camera)
outlinePass.edgeStrength = 5.0
outlinePass.edgeGlow = 1
outlinePass.usePatternTexture = false
outlinePass.edgeThickness = 1.0
outlinePass.downSampleRatio = 1
outlinePass.visibleEdgeColor.set(parseInt(0xffff00))
outlinePass.clear = true
composeroutline.addPass(outlinePass)
var FXAAShaderPass = new ShaderPass(FXAAShader)
const pixelRatio = renderer.getPixelRatio()
const width = document.getElementById('threecanvas').offsetWidth
const height = document.getElementById('threecanvas').offsetHeight
FXAAShaderPass.uniforms['resolution'].value.set(1 / (width * pixelRatio), 1 / (height * pixelRatio))
FXAAShaderPass.renderToScreen = true
composeroutline.addPass(FXAAShaderPass)
}
渲染
function render() {
update()
requestAnimationFrame(render)
composeroutline.render()
}
应用
可以通过鼠标悬停事件,添加悬停效果 添加 鼠标悬停事件 和 射线检测
window.addEventListener('pointermove', this.onPointermove, false)
this.raycaster = new THREE.Raycaster()
this.mouse = new THREE.Vector2()
然后通过判断鼠标悬停 或 点击事件时射线选中的模型,来添加选中事件 判断如果ds8这个模型显示,直接把射线检测给到ds8下的所有子模型,如果选中的是ds8下的子模型,则把ds8给到 outlinePass.selectedObjects 的数组,就相当于选中了ds8。 如果选中的不是ds8这个模型,则置空 outlinePass.selectedObjects 的数组,去掉原来的选中框
onPointermove(event) {
this.mouse.x = (event.offsetX / document.getElementById('threecanvas').offsetWidth) * 2 - 1
this.mouse.y = -(event.offsetY / document.getElementById('threecanvas').offsetHeight) * 2 + 1
this.raycaster.setFromCamera(this.mouse, camera)
if( ds8.visible === true){
const intersectsall = this.raycaster.intersectObjects(ds8.children, true)[0]
if (intersectsall.object.parent.parent.name === '选中') {
outlinePass.selectedObjects = [ds8]
} else {
outlinePass.selectedObjects = []
}
}
}
效果可参考 threejs官网示例
|