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

如何在Forge Viewer中拍摄无过多边距的模型截图?

在Forge Viewer中生成无多余边距的模型截图

要解决截图存在多余边距的问题,别依赖默认适配或截图功能,得精确控制相机视角和画布裁剪范围,以下是可行方案:

1. 获取模型的精确包围盒

先拿到模型(或多场景合并)的完整包围盒,这是后续调整的基础:

// 单模型场景
const bbox = viewer.model.getBoundingBox();
// 多模型场景,合并所有模型的包围盒
const combinedBbox = new THREE.Box3();
viewer.modelQueue.getModels().forEach(model => {
  combinedBbox.union(model.getBoundingBox());
});
// 提取中心和最大维度,用于计算相机距离
const center = bbox.center(); // 多模型替换为combinedBbox.center()
const size = bbox.getSize();
const maxDim = Math.max(size.x, size.y, size.z);

2. 调整相机至无填充视角

默认fitBounds会留边距,手动设置适配参数强制模型填满视口:

// 关闭默认边距,第三个参数padding设为0
viewer.navigation.fitBounds(false, bbox, 0);
// 若需自定义视角,可直接计算相机位置
const fov = viewer.getFOV();
const distance = (maxDim / 2) / Math.tan(fov / 2);
viewer.navigation.setView(
  center,
  center.clone().add(new THREE.Vector3(distance, distance, distance)), // 相机位置
  new THREE.Vector3(0, 1, 0) // 向上方向
);

3. 精确裁剪画布生成截图

如果调整相机后仍有少量边距,直接从画布裁剪模型对应的区域:

// 获取模型在屏幕上的坐标范围(注意Viewer屏幕Y轴反向)
const min = new THREE.Vector3();
const max = new THREE.Vector3();
bbox.getMin(min);
bbox.getMax(max);
const screenMin = viewer.worldToScreen(min);
const screenMax = viewer.worldToScreen(max);

// 从原画布裁剪对应区域
const canvas = viewer.canvas;
const cropWidth = Math.round(screenMax.x - screenMin.x);
const cropHeight = Math.round(screenMax.y - screenMin.y);
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = cropWidth;
croppedCanvas.height = cropHeight;
const croppedCtx = croppedCanvas.getContext('2d');

// 转换Y坐标:canvas的Y轴向下,Viewer的屏幕Y轴向上
croppedCtx.drawImage(
  canvas,
  screenMin.x,
  canvas.height - screenMax.y,
  cropWidth,
  cropHeight,
  0,
  0,
  cropWidth,
  cropHeight
);

// 转换为图片使用
const screenshotImg = new Image();
screenshotImg.src = croppedCanvas.toDataURL('image/png');

注意事项

  • 若场景有隐藏元素,先过滤确保包围盒仅包含可见模型
  • 部分浏览器对跨域画布有限制,需给模型资源配置CORS

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:29:55