2017-05-30 62 views
1

我在D3.js中相当新,我想构建一个实时协作黑板。一个管理员客户端在svg上绘制路径并且其他客户端接收它们。我试图从客户端挑选最后一个路径元素。我走过去几个小时,发现几个职位为How can I select :last-child in d3.js?,但无法使其工作。当我问:用d3.js选择svg的最后一个路径

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> 

感谢

回答

1

你有没有尝试过这样的事情?

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

您应该可以在d3选择api中使用像:last-child这样的字符串。

+0

我得到svg = {“_ groups”:[[{}]],“_ parents”:[{}]}无论我绘制多少路径。我认为唯一的解决方案是在svg.select(“path”)返回第一个元素的情况下在svg上反转路径元素。但它不是一个优雅的解决方案 – nick314

+0

嗯...当你'console.log(d3.select('svg')。node())''会发生什么? – Peter

+0

always svg = null ... – nick314

2

彼得的answer工作。

你得到一个{"_groups":[[{}]],"_parents":[{}]},因为你在your comment说,因为这是一个D3选择,那是预期的目标。

如果你想要得到的DOM元素,只需使用node()功能:

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

这里是一个演示使用SVG,它会记录空的路径,这是最后一个(因为SO片段冻结—至少在我的机器,尝试登录D3选择,here is a fiddle代码相同),当使用Chrome —:

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>