我使用 d3.js 在 javascript 中绘制散点图,这是我的第一个 JavaScript 程序。用户可以绘制单击n拖动SVGRectangle来计算由矩形限定的点的平均值。我已经实现了矩形绘图部分,我坚持使用必须确定矩形内哪些点(SVGCircles)的部分。我试图获取数组中的所有圆形元素allCircles,然后过滤掉矩形区域中的圆圈。但是,我不知道如何获取圆圈的坐标。我在下面的做法似乎不起作用。
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var allCircles = svg.selectAll("circle.circles"); //circles is the class for all points
//I have to do the following line coz for some reason the entire array comes as one single //element
allCircles = allCircles[0];
for (var j = 0; j < allCircles.length; j++) {
if (allCircles[j].top > startY && allCircles[j].left > startX
&& (allCircles[j].height + allCircles[j].top) < rectHeight + startY
&& (allCircles[j].width + allCircles[j].left) < rectWidth + startX) {
selectedCircles.push(allCircles[j]);
}
}
任何修复,建议,提示,链接将不胜感激,因为我的时间真的很短!
D3 选择对象时,无法直接访问这些属性 - 使用 .attr()
函数。也就是说,而不是allCircles[j].top
你会做d3.select(allCircles[j]).attr("top")
或allCircles[j].getAttribute("top")
.请注意,您需要显式设置这些属性。
执行类似操作的 D3 方法是在选择中使用 .filter()
函数,即类似
svg.selectAll("circle.circles")
.filter(function(d) { return d.top > startY && /* etc */; })
.each(function(d) {
// do something with the selected circles
});