是否有一种简单的方法可以在D3垂直条形图的条形图顶部放置圆角?我一直在玩.attr(“rx”,3),这似乎影响了酒吧的所有四个角落。
答案 0 :(得分:4)
您无法指定要在SVG中进行舍入的角落:rx
会影响所有4个角落。
唯一的解决方案是使用路径来模拟矩形。此函数返回一个圆角的路径:
function rectangle(x, y, width, height, radius){
return "M" + (x + radius) + "," + y + "h" + (width - 2*radius)
+ "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" +
(height - 2*radius) + "v" + radius + "h" + -radius + "h" +
(2*radius - width) + "h" + -radius + "v" + -radius + "v" +
(2*radius - height) + "a" + radius + "," + radius + " 0 0 1 "
+ radius + "," + -radius + "z";
};
这是一个演示片段,显示"条形图"使用这些路径,半径(此处rx
等效)为5px:
function rectangle(x, y, width, height, radius){
return "M" + (x + radius) + "," + y + "h" + (width - 2*radius) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" + (height - 2*radius) + "v" + radius + "h" + -radius + "h" + (2*radius - width) + "h" + -radius + "v" + -radius + "v" + (2*radius - height) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + -radius + "z";
};
var data = [40, 50, 30, 40, 90, 54, 20, 35, 60, 42];
var svg = d3.select("body")
.append("svg")
.attr("width", 400)
.attr("height", 120);
var rects = svg.selectAll(".paths").data(data).enter().append("path");
rects.attr("d", function(d,i){ return rectangle(10+40*i,100-d,20,d,5)});
var texts = svg.selectAll(".text").data("ABCDEFGHIJ".split("")).enter().append("text").attr("y",114).attr("x", function(d,i){return 16+40*i}).text(function(d){return d});

path {
fill:teal;
}
text {
fill:darkslategray;
font-size: 12px;
}

<script src="https://d3js.org/d3.v4.min.js"></script>
&#13;
PS:我没有写这个功能,它是基于M. Bostock和R. Longson的these answers。