撰寫 Viewer 擴展(Extension)

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

相關文章
相關標籤/搜索