Cytoscape.js: 将渲染位置转换为模型位置

Cytoscape.js: Convert a rendered position to a model position

如何转换 rendered position to a model position

示例:

var rpos = cy.pan(); 
var mpos = cy.toModelPosition(rpos); // Get top left corner position in model

据我所知,doc没有提到任何转换方法。我相信它会非常有用!

当然,我可以自己写点东西:

function toModelPosition(pos) {
    return {
        x: (pos.x - cy.pan().x) / cy.zoom(),
        y: (pos.y - cy.pan().y) / cy.zoom(),
    };
}

您通常不需要转换它们,因为 api 中的函数允许您传递任何一个值。

就像@maxkfranz 提到的,Cytoscape API 的大多数函数都接受这两种格式。

但我需要转换以供自己使用。所以这就是我最终做的事情:

// Convert a rendered position to a model position
cy.toModelPosition = (pos) => {
    const pan = cy.pan();
    const zoom = cy.zoom();
    return {
        x: (pos.x - pan.x) / zoom,
        y: (pos.y - pan.y) / zoom,
    };
};
// Convert a model position to a rendered position
cy.toRenderedPosition = (pos) => {
    const pan = cy.pan();
    const zoom = cy.zoom();
    return {
        x: pos.x * zoom + pan.x,
        y: pos.y * zoom + pan.y,
    };
};