首页 > 解决方案 > Forge Viewer: How to convert arbitrary client point to world point

问题描述

I am struggling with something right now. I have a page implementing the viewer with an extension that is using the ToolInterface so that I can capture mouse events. I am successfully getting mouse events and can retrieve the x, y coordinates that were returned.

What I would like to do is get the world (x, y, z) coordinates for that point. I tried to use the Viewer3D.clientToWorld function, but that always returns null regardless of whether the point is over geometry or not.

I also tried to use the ViewingUtilites.getHitPoint function to get the world (x, y, z) coordinates, but it always returns null as well. I tried to use (x, y) as returned by the event and also normalized.

So my question is, how do I get the world (x, y, z) coordinates from the client (x, y) coordinates in the Forge viewer?

Thank you!

**** EDITS: Code added below

MyViewerTool = function (viewer, options) {

Autodesk.Viewing.Extension.call(this, viewer, options);

var _self = this;
var _viewer = viewer;

// ....
_self.tool = null;

function MyViewerTool(viewer, toolName) {

    function normalizePoint(screenPoint) {
        const viewport = _viewer.navigation.getScreenViewport();
        var n = {
            x: (screenPoint.x - viewport.left) / viewport.width,
            y: (screenPoint.y - viewport.height) / viewport.height
        }

        return n;
    }

    this.handleSingleClick = function(event, button) {
        console.log(event);
        const normalizedPoint = normalizePoint({ x: event.clientX, y: event.clientY });
        const worldPoint = _viewer.utilities.getHitPoint(normalizedPoint.x, normalizedPoint.y);
        console.log(worldPoint);
        return false;
    };

    // ...
}
// other code that just does the register/load/etc
// this does load in the viewer as I am able to
// set a breakpoint above and I see what looks like
// valid point data.
// my first try used the clientToWorld(...)
// using the same event data passed in handleSingleClick (above).
//

标签: autodesk-forgeautodesk-viewer

解决方案


您可以使用查看器的clientToWorld(x, y, ignoreTransparent)功能。

示例实现:

let canvas = this.viewer.canvas;
let drag = false;

canvas.addEventListener('mousedown', () => drag = false);
canvas.addEventListener('mousemove', () => drag = true);
canvas.addEventListener('mouseup', (evt) => {        
    if (!drag) {
        var hitTest = this.viewer.clientToWorld(evt.offsetX, evt.offsetY, true);
        if (hitTest) {                   
            let x = hitTest.point.x;
            let y = hitTest.point.y;
            let z = hitTest.point.z;
        }
    }
});    

注意 offsetX 和 offsetY 的使用。


推荐阅读