转换后的D3鼠标坐标

时间:2018-06-26 19:23:15

标签: d3.js transform mousemove

我有一个看起来像这样的网络拓扑视图。它由节点和链接组成。我有一个在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 - After translate wrong mouse coordinates being reported. Why?

以及此解决方案:D3 click coordinates after pan and zoom

1 个答案:

答案 0 :(得分:0)

鼠标坐标是相对于整个svg的,而不是相对于具有转换的网络可缩放区域的。 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;});
        }
    }