消除矩形过渡期间的边界半径

时间:2014-02-18 12:13:41

标签: javascript css svg d3.js

如何设置条形图以便在我的图表中设置border-radius,如下面的快照中所示?

enter image description here

以下是我的尝试:

我选择了所有rect并做了,

  .attr("rx", 10)
  .attr("ry", 10)

did not give desired effect 我引用了示例here

我该如何解决这个问题?

jsFiddle

1 个答案:

答案 0 :(得分:1)

<rect> SVG元素不允许仅舍入某些特定角点。您必须使用<path> SVG元素。您可以使用svg / d3.js rounded corner on one corner of a rectangle中stackmate给出的函数来构建路径:

x: x-coordinate
y: y-coordinate
w: width
h: height
r: corner radius
tl: top_left rounded?
tr: top_right rounded?
bl: bottom_left rounded?
br: bottom_right rounded?

function rounded_rect(x, y, w, h, r, tl, tr, bl, br) {
    var retval;
    retval  = "M" + (x + r) + "," + y;
    retval += "h" + (w - 2*r);
    if (tr) { retval += "a" + r + "," + r + " 0 0 1 " + r + "," + r; }
    else { retval += "h" + r; retval += "v" + r; }
    retval += "v" + (h - 2*r);
    if (br) { retval += "a" + r + "," + r + " 0 0 1 " + -r + "," + r; }
    else { retval += "v" + r; retval += "h" + -r; }
    retval += "h" + (2*r - w);
    if (bl) { retval += "a" + r + "," + r + " 0 0 1 " + -r + "," + -r; }
    else { retval += "h" + -r; retval += "v" + -r; }
    retval += "v" + (2*r - h);
    if (tl) { retval += "a" + r + "," + r + " 0 0 1 " + r + "," + -r; }
    else { retval += "v" + -r; retval += "h" + r; }
    retval += "z";
    return retval;
}

然后你必须在D3.js attr()函数中调用这个函数。第一个参数是"d"与路径字符串对应的<path>属性的名称,第二个属性是从数据生成此字符串的函数。

episode.selectAll("rect")
   .data(function(d) { return d.ages;})
   .enter()
   .append("path")
   .attr("d",function(d){
               var round;
               if(d.y0==0){
                 round=false;
               }else{
                 round=true;
               }
               return rounded_rect(0,
                                   y(d.y1),
                                   x.rangeBand(),
                                   y(d.y0)-y(d.y1),
                                   10,round,round,false,false);})
    .style("fill", function(d) { return color(d.name); });  

这是你的jsFiddle的fork四舍五入的矩形,如你的快照。