three.js 选中模型

模型加载容器 webgl,可以是一个非满屏的容器

监听鼠标点击事件

通过 Raycaster 和 Vector2,获取模型和鼠标点击点的交汇
function getIntersects(x, y) {
  // x/y 是鼠标点击点距页面左/上距离 
  var raycaster = new THREE.Raycaster()
  var mouseVector = new THREE.Vector2() 

  let { camera, scene } = render
  let dom = document.getElementById('webgl')
  let width = dom.clientWidth;
  let height = dom.clientHeight;
  // 当前容器距页面上/左的距离
  let offsetTop = dom.offsetTop
  let offsetLeft = dom.offsetLeft
  x = ((x - offsetLeft) / width) * 2 - 1
  y = -((y - offsetTop) / height) * 2 + 1
  mouseVector.set(x, y);

  raycaster.setFromCamera(mouseVector, camera);

  return raycaster.intersectObjects(scene.children, true)
}
点击事件,处理选中的逻辑
function clickFn(event) {
    event.preventDefault()
    if (selectMesh) {
      // 再次点击时,恢复之前选中模型的颜色
      selectMesh.material.color.set(selectMeshColor)
      // 清空存储
      selectMesh = null
    }

    var intersects = getIntersects(event.layerX, event.layerY)
    if (intersects.length > 0) {
        var res = intersects.filter(function(res) {
            return res && res.object
        })[0]
        if (res && res.object) {
          selectMesh = res.object
          selectMeshColor = JSON.parse(JSON.stringify(res.object.material)).color
          // 更改选中模型颜色
          res.object.material.color.set("#fde308")
        }
    }
}

你可能感兴趣的:(three.js 选中模型)