我是javascript的新手,我想画这样的东西:
但我最终只能画出这样的矩形:
Rectangle(data){
this.canvas.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('data-id', (d) => d.matchId)
.attr('data-algorithm', (d) => d.algorithm)
.attr('class', 'match match__rectangle')
.attr('x', (d) => d.x)
.attr('y', (d) => d.y)
.attr('width', (d) => d.width)
.attr('height', (d) => d.height)
.style('fill', 'none')
.style('stroke', (d) => d.color);
}
有人可以帮助我在矩形的每一行的端点绘制那些小圆圈吗?
我是否需要重新考虑绘制线条和圆圈然后连接它们,或者我可以使用rect这样做吗?
谢谢!
答案 0 :(得分:1)
有几种方法可以绘制这些圆圈,而更合适的方法取决于你想用它们做什么。
例如,如果您不想将任何(有意义的)数据绑定到这些圈子,您可以使用带有矩形选择的each
来获取每个矩形的角并附加圆圈(到SVG,而不是矩形,这是不可能的。)
因此,对于每个矩形,我们得到四个圆的坐标......
var circlePositions = [
[d.x, d.y],
[d.x + d.width, d.y],
[d.x, d.y + d.height],
[d.x + d.width, d.y + d.height]
];
...并追加他们:
svg.selectAll(null)
.data(circlePositions)
.enter()
.append("circle")
.attr("cx", d => d[0])
.attr("cy", d => d[1])
这是一个包含伪造数据的演示,适用于3个矩形:
var data = [{x: 20, y: 20, width: 100, height: 20},
{x: 200, y: 80, width: 50, height: 120},
{x: 360, y: 50, width: 120, height: 80}];
var svg = d3.select("svg");
var rects = svg.selectAll(null)
.data(data)
.enter()
.append("rect")
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('width', d => d.width)
.attr('height', d => d.height)
.style('fill', 'gray')
.style('stroke', 'black');
rects.each(d => {
var circlePositions = [
[d.x, d.y],
[d.x + d.width, d.y],
[d.x, d.y + d.height],
[d.x + d.width, d.y + d.height]
];
svg.selectAll(null)
.data(circlePositions)
.enter()
.append("circle")
.attr("cx", d => d[0])
.attr("cy", d => d[1])
.attr("r", 6)
.attr("fill", "limegreen")
.attr("stroke", "black")
})
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="500" height="300"></svg>