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

Forge Data Visualization如何实现点击Sprite弹出信息弹窗

Forge Dataviz 点击Sprite弹出信息实现思路

实现核心逻辑

整个效果只需要做3件事:提前写好隐藏的弹窗DOM、在Sprite点击回调里触发弹窗显示、把3D场景里的Sprite位置转换为网页屏幕坐标给弹窗定位。

1. 先准备弹窗基础结构和样式

你可以直接用原生HTML/CSS写一个默认隐藏的弹窗组件,不需要额外引入第三方库:

<!-- 弹窗DOM,默认隐藏 -->
<div id="sprite-popup" style="display: none; position: absolute; background: #fff; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.15); padding: 12px 16px; z-index: 1000; width: 220px;">
  <h4 id="popup-title" style="margin: 0 0 8px 0; font-size: 16px;"></h4>
  <p id="popup-content" style="margin: 0; font-size: 14px; color: #666;"></p>
</div>

2. 在Sprite点击回调里处理弹窗逻辑

你之前已经完成了Sprite的事件配置,只需要在原有的点击回调里补充以下逻辑即可:

// 假设这是你已经配置好的Sprite点击事件回调
sprite.onClick = (event) => {
  // 1. 拿到你事先存在Sprite里的自定义数据,比如设备名称、实时参数等
  const spriteData = sprite.userData;
  // 2. 获取弹窗DOM
  const popup = document.getElementById('sprite-popup');
  const titleEl = document.getElementById('popup-title');
  const contentEl = document.getElementById('popup-content');
  // 3. 填充弹窗内容
  titleEl.innerText = spriteData.deviceName;
  contentEl.innerText = `当前温度:${spriteData.temperature}℃\n运行状态:正常`;
  // 4. 将Sprite的3D世界坐标转换为网页屏幕坐标
  const worldPos = sprite.getWorldPosition();
  const screenPos = viewer.worldToClient(new THREE.Vector3(worldPos.x, worldPos.y, worldPos.z));
  // 5. 设置弹窗位置,加10px偏移避免挡住Sprite
  popup.style.left = `${screenPos.x + 10}px`;
  popup.style.top = `${screenPos.y + 10}px`;
  // 6. 显示弹窗
  popup.style.display = 'block';
}

3. 补充关闭弹窗的逻辑

可以加个点击场景空白处关闭弹窗的逻辑,使用体验更好:

viewer.addEventListener('click', (event) => {
  // 判断点击的是不是Sprite,如果不是就关闭弹窗
  if (!event.target?.isSprite) {
    document.getElementById('sprite-popup').style.display = 'none';
  }
})

注意事项

  • 弹窗的position必须设为absolute,父级元素最好是和Viewer画布同级的position: relative节点,避免定位偏移
  • 如果需要弹窗跟随视角移动,可以在viewer的相机更新事件里重复执行坐标转换和定位逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:36:03