Forge Viewer 提供了一个扩展机制让客户撰写代码来增长 Viewer 的功能,并且透过这个机制编写出来的自订扩展不需从新载入模型就能够执行,那么要怎么撰写自个的扩展呢?这其实颇简单的,只要去继承 Autodesk.Viewing.Extension
编写自个的扩展代码,在透过调用 Viewer3D.loadExtension
这个函数就能够了,要卸载的话,也只要调用Viewer3D.loadExtension
函数就好了。Autodesk.Viewing.Extension
原型长的像这样(以 TypeScript 表示):app
class Extension { viewer: Viewer3D; options: Object?; id: string; /** * @param viewer The viewer to be extended. * @param options An optional dictionary of options for this extension. */ constructor( viewer: Viewer3D, options: Object ); /** * Override the load method to add functionality to the viewer. * Use the Viewer's APIs to add/modify/replace/delete UI, register event listeners, etc. * @return True if the load was successful. */ load(): boolean; /** * Override the unload method to perform some cleanup of operations that were done in load. * @return True if the unload was successful. */ unload(): boolean; /** * Gets the extension state as a plain object. Intended to be called when viewer state is requested. * @param viewerState Object to inject extension values. * @virtual */ getState( viewerState: Object ): void; /** * Restores the extension state from a given object. * @param viewerState Viewer state. * @param immediate Whether the new view is applied with (true) or without transition (false). * @return True if restore operation was successful. */ restoreState( viewerState: Object, immediate: boolean ): void; /** * Returns an object that persists throughout an extension's unload->load * operation sequence. Cache object is kept at ViewingApplication level. * Cache object lives only in RAM, there is no localStorage persistence. * @return The cache object for a given extension. */ getCache(): Object; }
这写提供一个简单的示例来讲明如何编写自个的代码,这个代码主要是透过编写扩展来改变 Viewer
的背景颜色(以ES2015表示):ide
class MyExtension extends Autodesk.Viewing.Extension { constructor( viewer, options ) { super( viewer, options ); } load() { // 将背景颜色改为红色 this.viewer.setBackgroundColor( 255, 0, 0, 255, 255, 255 ); return true; } unload() { // 将背景颜色改回来 Viewer3D 自带的 this.viewer.setBackgroundColor( 160,176,184, 190,207,216 ); return true; } } // 将自订的扩展注册到 Viewer 的扩展管理员里,`DemoExtension` 是这个自订扩展独有的名字, // 是在跟扩展管理员说我这个自订扩展叫作 `DemoExtension`,`Viewer3D` 也是透过这个名字来辨别要载入哪个扩展的 Autodesk.Viewing.theExtensionManager.registerExtension( 'DemoExtension', MyExtension );
扩展编写完了就能够透过下方的方法让 Viewer
载入或卸载:函数
// 载入自订扩展,并执行 `DemoExtension.load` 这个函数内的代码 viewer.loadExtension( 'DemoExtension', null ); // 卸载自订扩展,并执行 `DemoExtension.unload` 这个函数内的代码 viewer.unloadExtension( 'DemoExtension' );
这样是否是很简单呢~this