React中Autodesk Viewer动态加载自托管模型问题咨询
Autodesk Viewer React动态加载自有服务器模型及多模型实现
单个模型动态加载修复
你的现有代码存在两处关键问题:一是回调函数调用时未传递必要参数且this指向错误,二是自行托管的模型无需通过Document.load加载,直接使用viewer.loadModel更适配场景。修改后的核心代码如下:
class ViewerComponent extends React.Component { constructor(props) { super(props); this.container = React.createRef(); this.viewer = null; } componentDidMount() { // 初始化Viewer实例 this.viewer = new Autodesk.Viewing.Viewer3D(this.container.current); // 加载初始模型(若props传入路径) this.props.path && this.loadModel(this.props.path); } componentDidUpdate(prevProps) { this.updateViewerState(prevProps); } // 封装模型加载逻辑 loadModel(modelPath) { // 卸载当前模型(实现模型替换) this.viewer.model && this.viewer.unloadModel(this.viewer.model); // 加载自有服务器上的模型(支持SVF、SVF2、GLB等格式) this.viewer.loadModel( modelPath, {}, () => console.log('模型加载成功'), (code, msg) => console.error('模型加载失败:', code, msg) ); } // 监听props变化更新Viewer状态 updateViewerState(prevProps) { if (this.props.path && this.props.path !== prevProps.path) { this.loadModel(this.props.path); } else if (!this.props.path && this.viewer.model) { this.viewer.unloadModel(this.viewer.model); } } componentWillUnmount() { this.viewer?.finish(); } render() { return <div ref={this.container} style={{ width: '100%', height: '100vh' }} />; } }
多模型加载(AggregatedView)实现
若要实现多模型叠加,需启用Viewer的聚合视图模式,加载时保留当前模型。核心代码示例:
componentDidMount() { this.viewer = new Autodesk.Viewing.Viewer3D(this.container.current); // 启用聚合视图模式,支持多模型加载 this.viewer.startAggregate(); // 批量加载初始多模型 this.props.modelPaths?.forEach(path => this.loadMultiModel(path)); } // 多模型加载方法 loadMultiModel(modelPath) { this.viewer.loadModel( modelPath, { keepCurrentModel: true }, // 保留已加载模型,实现叠加 () => console.log('模型加载成功'), (code, msg) => console.error('模型加载失败:', code, msg) ); } // 动态更新多模型列表 updateViewerState(prevProps) { const currPaths = this.props.modelPaths || []; const prevPaths = prevProps.modelPaths || []; if (JSON.stringify(currPaths) !== JSON.stringify(prevPaths)) { // 清空所有已加载模型 this.viewer.impl.unloadAllModels(); // 加载新的模型列表 currPaths.forEach(path => this.loadMultiModel(path)); } }
注意事项
- 自有服务器托管的模型需为Viewer支持的格式(SVF、SVF2、GLB等),且服务器需配置CORS规则,允许Viewer所在域名跨域访问。
- 若模型是Forge转换后的完整文档(含
manifest.json),可改用Autodesk.Viewing.Document.load加载,需确保路径指向manifest.json,并在回调中加载文档节点:loadDocumentModel(docPath) { Autodesk.Viewing.Document.load( docPath, (doc) => { const viewables = doc.getRoot().getDefaultGeometry(); this.viewer.loadDocumentNode(doc, viewables, { keepCurrentModel: true }); }, (code, msg) => console.error('文档加载失败:', code, msg) ); }
内容的提问来源于stack exchange,提问作者Bas Nederveen
相关产品推荐
相关产品推荐

