使用D3.J.选择SVG的最后路径



我在d3.js中是相当新的,我想建立一个与黑板协作的实时。一位管理员客户在SVG上绘制路径,而其他客户会收到它们。我正在尝试从客户端选择最后的路径元素。我在过去的几个小时里走了几个小时,找到了几个帖子,我该如何选择:D3.js中的最后孩子?但不能使它起作用。当我问:

 console.log('svg ='+svg.selectAll("path")

绘制了两条路径,我得到了

svg ={"_groups":[{"0":{},"1":{}}],"_parents":[{"__on":[{"type":"click","name":"","capture":false},{"type":"mousedown","name":"drag","capture":false},{"type":"touchstart","name":"drag","capture":false},{"type":"touchmove","name":"drag","capture":false},{"type":"touchend","name":"drag","capture":false},{"type":"touchcancel","name":"drag","capture":false}]}]}  

编辑:我的DOM结构

<svg id="myCanvas" width="960" height="500">
            <rect fill="#F2EDE4" width="100%" height="100%"></rect>
        <path fill="none" stroke="black" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" d="M223.64999389648438,304.25L223.98332722981772,304.5833333333333C224.31666056315103,304.9166666666667,224.98332722981772,305.5833333333333,226.31666056315103,306.75C227.64999389648438,307.9166666666667,229.64999389648438,309.5833333333333,231.14999389648438,310.4166666666667C232.64999389648438,311.25,233.64999389648438,311.25,234.98332722981772,310.4166666666667C236.31666056315103,309.5833333333333,237.98332722981772,307.9166666666667,238.81666056315103,307.0833333333333L239.64999389648438,306.25"></path><path></path></svg>

预先感谢

您是否尝试过类似的事情?

const lastPath = d3.select('svg>path:last-child')

您应该能够在D3选择API中使用:last-child之类的字符串。

peter的答案工作。

正如您在评论中所说的那样,您会得到{"_groups":[[{}]],"_parents":[{}]}

如果要获得DOM元素,只需使用node()函数:

const lastPath = d3.select('svg>path:last-child').node();
//getting the DOM element -------------------------^

这是一个使用您的SVG的演示,它将记录那个空路径,这是最后一个(因为S.O. smippets Freeze&mdash;至少在我的计算机中,使用Chrome&Mdash;在尝试记录D3选择时,这是一个带有相同代码的小提琴(:

const lastPath = d3.select('svg>path:last-child').node();
console.log(lastPath)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="myCanvas" width="960" height="500">
  <rect fill="#F2EDE4" width="100%" height="100%"></rect>
  <path fill="none" stroke="black" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" d="M223.64999389648438,304.25L223.98332722981772,304.5833333333333C224.31666056315103,304.9166666666667,224.98332722981772,305.5833333333333,226.31666056315103,306.75C227.64999389648438,307.9166666666667,229.64999389648438,309.5833333333333,231.14999389648438,310.4166666666667C232.64999389648438,311.25,233.64999389648438,311.25,234.98332722981772,310.4166666666667C236.31666056315103,309.5833333333333,237.98332722981772,307.9166666666667,238.81666056315103,307.0833333333333L239.64999389648438,306.25"></path>
  <path></path>
</svg>

这是我解决这个问题的原因。根据D3.Selections文档,这是您应该做的:

var lastPath = d3.selectAll('svg>path').filter(':last-child');

相关内容

最新更新