[英]Accessing array elements in d3.js
I want the user to be able to draw a line on an SVG canvas. 我希望用户能够在SVG画布上画一条线。 At first, a "rough path" consisting of 1px by 1px rectangles is shown, then when the user releases the mouse, the line he traced is converted into a SVG
<path>
. 首先,显示了一个由1px x 1px矩形组成的“粗糙路径”,然后当用户释放鼠标时,他跟踪的行将转换为SVG
<path>
。 This is the code that creates the rectangles: 这是创建矩形的代码:
var svg = d3.select('#svg-overlay'); //SVG Canvas
var roughPath = [];
( ... )
var tx = Math.round(e.pageX - offset.left);
var ty = Math.round(e.pageY - offset.top);
roughPath.push(svg.append('rect')
.attr('width', 1)
.attr('height', 1)
.attr('x', tx)
.attr('y', ty)
.attr('fill', 'white'));
After the path has been drawn and converted into <path>
, I want to be able to remove all the rectangles stored in roughPath
. 绘制路径并将其转换为
<path>
,我希望能够删除所有存储在roughPath
的矩形。 However, I can't figure out how to reach the elements inside that array. 但是,我不知道如何到达该数组中的元素。
d3.select(roughPath)
didn't work, neither did d3.select(roughPath).selectAll('rect')
, nor roughPath.forEach(...)
. d3.select(roughPath)
不起作用, d3.select(roughPath).selectAll('rect')
也不roughPath.forEach(...)
。 Could someone pitch in a suggestion how I could reach d3 elements stored within an array, or at least how I could remove all elements within roughPath
? 有人可以提出一个建议,让我知道如何到达数组中存储的d3个元素,或者至少我如何删除
roughPath
中的所有元素吗?
Generally speaking, you shouldn't need to hold on to additional references to selections in your own structures (such as your roughPath
array). 一般来说,您不需要在自己的结构(例如您的
roughPath
数组)中保留对选择的其他引用。 Instead, think of the DOM as a collection of nodes (rects, in your case) that you can query using selectors. 而是将DOM视为可以使用选择器查询的节点(在您的情况下为矩形)的集合。
If you add a class to the nodes you create on your rough path you can use that to query the group of nodes: 如果将类添加到在粗略路径上创建的节点,则可以使用该类来查询节点组:
svg.append('rect')
.attr('class', 'roughpath')
.attr('width', 1)
.attr('height', 1)
.attr('x', tx)
.attr('y', ty)
.attr('fill', 'white');
Later, when you want to delete the nodes you can simply do: 以后,当您要删除节点时,只需执行以下操作:
svg.selectAll('rect.roughpath').remove();
Scott's answer is the most idiomatic way of doing what you're trying. Scott的答案是您尝试做的最惯用的方式。 If you really want to store the references in an array though, removing them is pretty simple:
如果您确实想将引用存储在数组中,则删除它们非常简单:
roughPath.forEach(function(d){ d.remove(); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.