如何在nuxt js autodesk forge viewer中使用IconMarkupExtension?

问题描述 投票:0回答:1

我试图通过下面的例子来使用IconMarkupExtension。

https:/forge.autodesk.comlogplacing-custom-markup-dbid。

我试着把它转换到nuxt js中使用,但当浏览者加载时,我已经创建了工具栏并显示了工具提示,但当我点击该工具栏时,没有添加任何标记。但是当浏览者加载时,我已经创建了工具栏并显示了工具提示,但是当我点击工具栏时,没有添加任何标记。

谁能纠正我的代码,使其在基于nuxt的应用程序中工作。我把我的示例代码放在下面。

/index.vue

    <template>
  <div>
    <div id="forgeViewer"></div>
  </div>
</template>

<script>

export default {
  components: {

  },  
  data(){
    return{

    }
  },
  mounted(){
      this.initAutodesk();
  },
  methods:{
    async initAutodesk(){
    var htmlDiv = document.getElementById('forgeViewer');
    const IconMarkupExtension = await import('./extensions/IconMarkupExtension.js').then(mod=>mod.default)
    Autodesk.Viewing.theExtensionManager.registerExtension('IconMarkupExtension', IconMarkupExtension);
    const viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv,{ extensions: ['IconMarkupExtension'] });
    window.viewer = viewer;
       window.viewer.loadExtension('IconMarkupExtension', {
            button: {
                icon: 'fa-thermometer-half',
                tooltip: 'Show Temperature'
            },
            icons: [
                { dbId: 1942,   label: '300&#176;C', css: 'fas fa-thermometer-full' },
                { dbId: 10876,    label: '356&#176;C', css: 'fas fa-thermometer-full' },
                { dbId: 2648,  label: '450&#176;C', css: 'fas fa-thermometer-empty' },
                { dbId: 2228,                         css: 'fas fa-exclamation-triangle' },
            ],
            onClick: (id) => {
                viewers.select(id);
                viewers.utilities.fitToView();
                switch (id){
                    case 2228:
                        alert('Sensor offline');
                }
            }
        })
    var options = {
        env: 'AutodeskProduction',
        api: 'derivativeV2',  // for models uploaded to EMEA change this option to 'derivativeV2_EU'
        getAccessToken: function(onTokenReady) {
          var token = 'eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5In0.eyJzY29wZSI6WyJjb2RlOmFsbCIsImRhdGE6d3JpdGUiLCJkYXRhOnJlYWQiLCJidWNrZXQ6Y3JlYXRlIiwiYnVja2V0OmRlbGV0ZSIsImJ1Y2tldDpyZWFkIl0sImNsaWVudF9pZCI6Ikp2Vk40bzdBQ0V0ZE81TVpnZ21QMk9WM1RoNFJnRW54IiwiYXVkIjoiaHR0cHM6Ly9hdXRvZGVzay5jb20vYXVkL2p3dGV4cDYwIiwianRpIjoiMkhNbElFTnhpVEthb3VueXpPN2NTUVNFeDhvMWJDWnlDYWs5WGVEM2c5V0xjbldRY3gwdXRsendhcG1tS3lkRyIsImV4cCI6MTU5MTE4NjIyN30.wmYOe6nZEo9IpWxVLtF1E6FUR4WRjNgF4BjNshzCZvI';
          var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
          onTokenReady(token, timeInSeconds);
        }
      };
    Autodesk.Viewing.Initializer(options, function() {
      var startedCode = viewer.start();
      if (startedCode > 0) {
        console.error('Failed to create a Viewer: WebGL not supported.');
        return;
      }
      console.log('Initialization complete, loading a model next...');
    });
    var documentId = 'urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZmFjaWxpb25ld2NsaWVudGJ1Y2tldC9yYWNfYWR2YW5jZWRfc2FtcGxlX3Byb2plY3QucnZ0';
    Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, this.onDocumentLoadFailure);
    function onDocumentLoadSuccess(viewerDocument) {
        var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
        viewer.loadDocumentNode(viewerDocument, defaultModel);
        viewer.addEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, event=>{
           console.log(event.dbIdArray.length);
        })
    }
  },
  onDocumentLoadFailure() {
      console.error('Failed fetching Forge manifest');
    },
  }
}
</script>

<style>
body {
    margin: 0;
  }
  #forgeViewer {
    width: 100%;
    height: 100%;
    margin: 0;
    background-color: #F0F8FF;
  }
</style>

页面扩展IconMarkupExtensions.js,我在控制台没有收到任何错误。

class IconMarkupExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this._group = null;
        this._button = null;
        this._icons = options.icons || [];
    }

    load() {
        const updateIconsCallback = () => {
            if (this._enabled) {
                this.updateIcons();
            }
        };
        this.viewer.addEventListener(Autodesk.Viewing.CAMERA_CHANGE_EVENT, updateIconsCallback);
        this.viewer.addEventListener(Autodesk.Viewing.ISOLATE_EVENT, updateIconsCallback);
        this.viewer.addEventListener(Autodesk.Viewing.HIDE_EVENT, updateIconsCallback);
        this.viewer.addEventListener(Autodesk.Viewing.SHOW_EVENT, updateIconsCallback);
        return true;
    }

    unload() {
        // Clean our UI elements if we added any
        if (this._group) {
            this._group.removeControl(this._button);
            if (this._group.getNumberOfControls() === 0) {
                this.viewer.toolbar.removeControl(this._group);
            }
        }

        return true;
    }

    onToolbarCreated() {
        // Create a new toolbar group if it doesn't exist
        this._group = this.viewer.toolbar.getControl('customExtensions');
        if (!this._group) {
            this._group = new Autodesk.Viewing.UI.ControlGroup('customExtensions');
            this.viewer.toolbar.addControl(this._group);
        }

        // Add a new button to the toolbar group
        this._button = new Autodesk.Viewing.UI.Button('IconExtension');
        this._button.onClick = (ev) => {
            this._enabled = !this._enabled;
            this.showIcons(this._enabled);
            this._button.setState(this._enabled ? 0 : 1);

        };
        this._button.setToolTip(this.options.button.tooltip);
        this._button.container.children[0].classList.add('fas', this.options.button.icon);
        this._group.addControl(this._button);
    }

    showIcons(show) {
        console.log('entering into showIcons')
        const $viewer = $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer');

        // remove previous...
        $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer label.markup').remove();
        if (!show) return;

        // do we have anything to show?
        if (this._icons === undefined || this.icons === null) return;

        // do we have access to the instance tree?
        const tree = this.viewer.model.getInstanceTree();
        if (tree === undefined) { console.log('Loading tree...'); return; }

        const onClick = (e) => {
            if (this.options.onClick)
                this.options.onClick($(e.currentTarget).data('id'));
        };

        this._frags = {}
        for (var i = 0; i < this._icons.length; i++) {
            // we need to collect all the fragIds for a given dbId
            const icon = this._icons[i];
            this._frags['dbId' + icon.dbId] = []

            // create the label for the dbId
            const $label = $(`
            <label class="markup update" data-id="${icon.dbId}">
                <span class="${icon.css}"> ${icon.label || ''}</span>
            </label>
            `);
            $label.css('display', this.viewer.isNodeVisible(icon.dbId) ? 'block' : 'none');
            $label.on('click', onClick);
            $viewer.append($label);

            // now collect the fragIds
            const _this = this;
            tree.enumNodeFragments(icon.dbId, function (fragId) {
                _this._frags['dbId' + icon.dbId].push(fragId);
                _this.updateIcons(); // re-position of each fragId found
            });
        }
    }

    getModifiedWorldBoundingBox(dbId) {
        var fragList = this.viewer.model.getFragmentList();
        const nodebBox = new THREE.Box3()

        // for each fragId on the list, get the bounding box
        for (const fragId of this._frags['dbId' + dbId]) {
            const fragbBox = new THREE.Box3();
            fragList.getWorldBounds(fragId, fragbBox);
            nodebBox.union(fragbBox); // create a unifed bounding box
        }

        return nodebBox
    }

    updateIcons() {
        for (const label of $('#' + this.viewer.clientContainer.id + ' div.adsk-viewing-viewer .update')) {
            const $label = $(label);
            const id = $label.data('id');

            // get the center of the dbId (based on its fragIds bounding boxes)
            const pos = this.viewer.worldToClient(this.getModifiedWorldBoundingBox(id).center());

            // position the label center to it
            $label.css('left', Math.floor(pos.x - $label[0].offsetWidth / 2) + 'px');
            $label.css('top', Math.floor(pos.y - $label[0].offsetHeight / 2) + 'px');
            $label.css('display', this.viewer.isNodeVisible(id) ? 'block' : 'none');
        }
    }
}

Autodesk.Viewing.theExtensionManager.registerExtension('IconMarkupExtension', IconMarkupExtension);

我在控制台中没有得到任何错误。而且在使用console.log调试的时候发现它进入了showIcons功能。但不知道是否要修改一下才能使其工作。给出的dbId是正确的,文件中就有。

先谢谢你了。

nuxt.js autodesk-forge autodesk-viewer
1个回答
0
投票

你是否应用了必要的CSS来正确显示图标?它们可以被发现 此处

因为我在你发布的代码的样式块中没有看到这些......

为了进一步排除故障,请检查标签是否在浏览器的devtools中渲染到了视口?如果有的话,请检查它们的样式,看看它们是否被遮住了,或者是否被定位在视口之外......

© www.soinside.com 2019 - 2024. All rights reserved.