D3变换后的鼠标坐标

3
我有一个网络拓扑视图,看起来像这样。它由节点和链接组成。我有一个按钮,可以在g.newLinks下创建一条线,其中一个坐标设置为节点,另一个坐标随着“mousemove”更新为鼠标坐标。这一切都能正常工作,直到我进行了转换,然后鼠标点和线x2和y2不再对齐。如何在转换后获取正确的鼠标坐标?

enter image description here

 addNewLineToNode(node: Node) {
    this.drawingNewLine = true;

    this.newLinkDatum = {
        source: node,
        target: { x: node.x, y: node.y }
    };

    this.svg.select('.newLinks').append('svg:line').attr('class', 'link');
}


 function moveNewLine(d: any, event: MouseEvent) {
        if (me.drawingNewLine) {
            var mouse = d3.mouse(this);

            if(isNaN(mouse[0])){
                //Do nothing we've already set target x and y
            } else {
                var mCoords = me.getMouseCoords({x: mouse[0], y:mouse[1]});
                me.newLinkDatum.target.x = mCoords.x;
                me.newLinkDatum.target.y = mCoords.y;
            }

            const newLink = me.svg
                .select('.newLinks')
                .selectAll('.link')
                .datum(me.newLinkDatum)
                .attr('x1', function(d: any) {return d['source'].x;})
                .attr('y1', function(d: any) {return d['source'].y;})
                .attr('x2', function(d: any) {return d['target'].x;})
                .attr('y2', function(d: any) {return d['target'].y;});
        }
    }


 getMouseCoords(point: any){
    var pt = this.svg.node().createSVGPoint();
    pt.x = point.x;
    pt.y = point.y;
    pt = pt.matrixTransform(this.svg.node().getCTM());
    return { x: pt.x, y: pt.y };
}

我尝试使用了这个解决方案(如上所示):d3.js - 翻译后报告错误的鼠标坐标。为什么?

还有这个解决方案:D3 平移和缩放后的点击坐标

1个回答

1
鼠标坐标是相对于整个svg而不是具有变换的network-zoomable-area。moveNewLine函数需要像这样:

 function moveNewLine(d: any, event: MouseEvent) {
        if (me.drawingNewLine) {

            var mouse = d3.mouse(me.svg.select('#network-zoomable-area').node());

            if(isNaN(mouse[0])){
                //Do nothing we've already set target x and y
            } else {
             //   var mCoords = me.getMouseCoords({x: mouse[0], y:mouse[1]});
                me.newLinkDatum.target.x = mouse[0];
                me.newLinkDatum.target.y = mouse[1];
            }

            const newLink = me.svg
                .select('.newLinks')
                .selectAll('.link')
                .datum(me.newLinkDatum)
                .attr('x1', function(d: any) {return d['source'].x;})
                .attr('y1', function(d: any) {return d['source'].y;})
                .attr('x2', function(d: any) {return d['target'].x;})
                .attr('y2', function(d: any) {return d['target'].y;});
        }
    } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接