svg/d3.js 在矩形的一个角上圆角 [英] svg / d3.js rounded corner on one corner of a rectangle

查看:46
本文介绍了svg/d3.js 在矩形的一个角上圆角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 svg 有一个内置函数来做圆角,但我只需要在四个角中的两个上做圆角.

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.

我知道我可以在彼此之上绘制多个矩形来模仿它,但这似乎有点俗气.有什么办法可以使用剪辑或任何 d3.js 方法来做到这一点?

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.

推荐答案

扩展 @robert-longson 的答案,您可以使用 SVG 的 椭圆弧命令lineto 命令 用于直边.这些与路径元素一起使用.这是一种可能的实现:

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";
}

然后您可以调用此函数来计算d"属性.例如:

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);
    });

现场示例:

可选:如果您愿意,可以重构 rightRoundedRect 函数以使其可配置,而不是采用大量参数.这种方法类似于 D3 的内置 形状生成器.例如,您可以像这样使用矩形生成器:

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.

这篇关于svg/d3.js 在矩形的一个角上圆角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆