You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Autodesk Viewer API实现Ctrl+点击精准添加单个构件至选中集

解决Autodesk Viewer Ctrl+点击多选无关构件的问题

Viewer默认选择逻辑会拾取所有与点击射线相交的构件,Ctrl+点击时会将这些构件全部追加到选中集,导致无关构件被选中。以下是通过API调整选择逻辑的具体方案:

实现精准Ctrl+点击单个构件的步骤

1. 禁用默认选择工具

先关闭Viewer自带的选择工具,避免其自动执行多构件拾取:

viewer.toolController.deactivateTool('selection');

2. 自定义选择交互逻辑

通过监听鼠标点击和Ctrl键状态,手动实现精准选择:

let isCtrlPressed = false;

// 监听Ctrl键的按下/抬起状态
document.addEventListener('keydown', e => {
  if (e.key === 'Control') isCtrlPressed = true;
});
document.addEventListener('keyup', e => {
  if (e.key === 'Control') isCtrlPressed = false;
});

// 监听Viewer的点击事件
viewer.addEventListener(Autodesk.Viewing.CLICK_EVENT, event => {
  // 手动执行hitTest,仅获取视觉最靠前的第一个构件
  const hitResults = viewer.impl.hitTest(event.clientX, event.clientY, true);
  if (!hitResults.length) return;
  const targetDbId = hitResults[0].dbId;

  if (isCtrlPressed) {
    // Ctrl+点击:追加/取消单个构件
    const currentSelection = viewer.getSelection();
    const newSelection = currentSelection.includes(targetDbId)
      ? currentSelection.filter(id => id !== targetDbId) // 再次点击取消选中
      : [...currentSelection, targetDbId]; // 追加新构件
    viewer.select(newSelection);
  } else {
    // 普通点击:替换为当前单个构件
    viewer.select([targetDbId]);
  }
});

3. 关键逻辑说明

  • 精准拾取:通过viewer.impl.hitTest获取拾取结果,只取第一个(最靠近相机的构件),避免默认的多构件命中
  • 选中集管理:根据Ctrl键状态,手动处理选中集的追加、取消或替换,完全控制选择行为
  • 交互优化:额外实现了“Ctrl+点击已选中构件取消选中”的逻辑,符合常规UI交互习惯

4. 恢复默认选择(可选)

如果需要在特定场景恢复Viewer默认选择行为,可重新激活默认工具:

viewer.toolController.activateTool('selection');

内容的提问来源于stack exchange,提问作者lijinkai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:41:05