[英]Accessing array elements in d3.js
我希望用戶能夠在SVG畫布上畫一條線。 首先,顯示了一個由1px x 1px矩形組成的“粗糙路徑”,然后當用戶釋放鼠標時,他跟蹤的行將轉換為SVG <path>
。 這是創建矩形的代碼:
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'));
繪制路徑並將其轉換為<path>
,我希望能夠刪除所有存儲在roughPath
的矩形。 但是,我不知道如何到達該數組中的元素。 d3.select(roughPath)
不起作用, d3.select(roughPath).selectAll('rect')
也不roughPath.forEach(...)
。 有人可以提出一個建議,讓我知道如何到達數組中存儲的d3個元素,或者至少我如何刪除roughPath
中的所有元素嗎?
一般來說,您不需要在自己的結構(例如您的roughPath
數組)中保留對選擇的其他引用。 而是將DOM視為可以使用選擇器查詢的節點(在您的情況下為矩形)的集合。
如果將類添加到在粗略路徑上創建的節點,則可以使用該類來查詢節點組:
svg.append('rect')
.attr('class', 'roughpath')
.attr('width', 1)
.attr('height', 1)
.attr('x', tx)
.attr('y', ty)
.attr('fill', 'white');
以后,當您要刪除節點時,只需執行以下操作:
svg.selectAll('rect.roughpath').remove();
Scott的答案是您嘗試做的最慣用的方式。 如果您確實想將引用存儲在數組中,則刪除它們非常簡單:
roughPath.forEach(function(d){ d.remove(); })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.