D3.js - 带圆角的堆积条形图

时间:2017-08-25 09:42:56

标签: javascript d3.js canvas svg html5-canvas

请指点我如何在堆积条形图中绘制D3.js圆角(仅适用于第一个和最后一个元素)。

当前为一个实例/一行堆叠条生成的SVG代码如下:

  <g class="layer" style="fill: rgb(247, 139, 157);">
    <rect rx="15" ry="15" y="104" x="51" height="21" width="100"></rect>
    <rect rx="15" ry="15" y="22" x="78" height="21" width="166"></rect>
    <rect rx="15" ry="15" y="227" x="48" height="21" width="341"></rect>
    <rect rx="15" ry="15" y="186" x="80" height="21" width="546"></rect>
    <rect rx="15" ry="15" y="145" x="80" height="21" width="418"></rect>
    <rect rx="15" ry="15" y="63" x="40" height="21" width="238"></rect>
  </g>

上面我补充道:

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

到所有甚至不符合我要求的矩形元素。 问题是如何只为边界元素(第一个和最后一个)添加角落?

1 个答案:

答案 0 :(得分:0)

虽然这不是一个程序化实现,但您的目标可能是:

<svg xmlns="http://www.w3.org/2000/svg" width="450" height="200">
  <defs>
    <clipPath id="cp1" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="104" width="141" height="21" rx="8" ry="8" />
    </clipPath>
    <clipPath id="cp2" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="22" width="234" height="21" rx="8" ry="8" />
    </clipPath>
    <clipPath id="cp3" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="227" width="379" height="21" rx="8" ry="8" />
    </clipPath>
    <clipPath id="cp4" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="145" width="170" height="21" rx="8" ry="8" />
    </clipPath>
    <clipPath id="cp5" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="63" width="268" height="21" rx="8" ry="8" />
    </clipPath>
  </defs>
  <g style="fill:#9df78b">
    <rect clip-path="url(#cp1)" x="10" y="104" width="41" height="21" />
    <rect clip-path="url(#cp2)" x="10" y="22" width="68" height="21" />
    <rect clip-path="url(#cp3)" x="10" y="227" width="38" height="21" />
    <rect clip-path="url(#cp4)" x="10" y="145" width="70" height="21" />
    <rect clip-path="url(#cp5)" x="10" y="63" width="30" height="21" />
  </g>
  <g style="fill:#f78b9d">
    <rect clip-path="url(#cp1)" x="51" y="104" width="100" height="21" />
    <rect clip-path="url(#cp2)" x="78" y="22" width="166" height="21" />
    <rect clip-path="url(#cp3)" x="48" y="227" width="341" height="21" />
    <rect clip-path="url(#cp4)" x="80" y="145" width="100" height="21" />
    <rect clip-path="url(#cp5)" x="40" y="63" width="238" height="21" />
  </g>
</svg>

属于同一堆栈的每个rect都获得相同的clip-path,带有圆角的clipPath rect从完整堆栈的下限到上限。