Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - svg / d3.js rounded corner on one corner of a rectangle

I know svg has an in built function to do rounded corners, but I need to do rounded corners on only 2 of the four corners.

I know I can draw multiple rectangles on top of each other to imitate that, but that seems kind of cheesy. Any way to do it using clipping or any d3.js method?

Right now I have a horizontal bar graph that has rects like:

    rects.enter().append("rect")
        .attr("x",function(d,i) { return x(0); })
        .attr("width",function(d) { return x(d.value) - x(0); })
        .attr("height",y.rangeBand())
        .attr("y",function(d) { return y(d.name); })

I'm trying to produce rounded corners on the right hand side of the rect, but not sure how to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Expanding on @robert-longson's answer, you can use SVG's elliptical arc commands to make the corners, in conjunction with lineto commands for the straight edges. These are used with path elements. Here's one possible implementation:

// Returns path data for a rectangle with rounded right corners.
// The top-left corner is ?x,y?.
function rightRoundedRect(x, y, width, height, radius) {
  return "M" + x + "," + y
       + "h" + (width - radius)
       + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius
       + "v" + (height - 2 * radius)
       + "a" + radius + "," + radius + " 0 0 1 " + -radius + "," + radius
       + "h" + (radius - width)
       + "z";
}

You can then call this function to compute the "d" attribute. For example:

rects.enter().append("path")
    .attr("d", function(d) {
      return rightRoundedRect(x(0), y(d.name), x(d.value) - x(0), y.rangeBand(), 10);
    });

Live example:

Optional: If you like, you could refactor the rightRoundedRect function to make it configurable, rather than taking lots of arguments. This approach would be similar to D3's built-in shape generators. For example, you might use a rect generator like so:

rects.enter().append("path")
    .attr("d", rightRoundedRect()
      .x(x(0))
      .y(function(d) { return y(d.name); })
      .width(function(d) { return x(d.value) - x(0); })
      .height(y.rangeBand())
      .radius(10));

For more details on that approach, see the configurable function tutorial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...