【问题标题】:Rounded corner only on one side of svg <rect>圆角仅在 svg <rect> 的一侧
【发布时间】:2016-04-27 16:57:17
【问题描述】:

我正在尝试实现类似图表的条形图。我有以下 html 元素

<rect x="35" y="-135" width="10" height="51" style="stroke: rgb(255, 255, 255); opacity: 0.8; fill: rgb(255, 122, 0);"></rect>

我想给矩形的顶部 一个圆角。 怎么可能?
我无法应用border-radius 属性。

【问题讨论】:

  • 您必须将其转换为路径并使用椭圆弧对角进行建模。

标签: html css svg


【解决方案1】:

您也可以使用clipPath。这是一种 hack,但可能更容易实现。

假设如下:

  • 您的rectwidth="10"height="51"
  • 顶角将是rx="5"ry="5"

<svg>
    <defs>
        <clipPath id="round-corner">
            <rect x="0" y="0" width="10" height="56" rx="5" ry="5"/>
         </clipPath>
     </defs>

     <!-- if you want to use x="35" y="-135" put clip-path on a `g` element --> 
     <rect width="10" 
           height="51" 
           clip-path="url(#round-corner)"
           style="stroke: rgb(255, 255, 255); opacity: 0.8; fill: rgb(255, 122, 0);"></rect>
</svg>

一些注意事项:
所以clipPath &gt; rect &gt; width 和你的rect 完全一样。

对于clipPath &gt; rect &gt; height,您必须考虑顶部的圆角半径,因此高度应为rect.height + desired-corner-radius(在本例中为51px + 5px)。

这样您就不会用clipPath 触摸矩形的底部。

【讨论】:

    【解决方案2】:

    正如Robert Longson 所评论的,您需要将您的矩形元素转换为path element 以控制圆角。

    在以下示例中,我使用cubic bezier curveQ 命令制作左上角圆角(d 属性中的Q1 1 5 1):

    svg{
      height:90vh;
      width:auto;
      }
    <svg viewbox="0 0 10 50">
      <path d="M1 49 V5 Q1 1 5 1 H9 V49z"
            fill="rgba(255, 122, 0, 0.8)" />
    </svg>

    【讨论】:

    • 使用贝塞尔曲线是不正确的。贝塞尔曲线只能逼近一个圆。您需要使用arc 命令:devdocs.io/svg/attribute/d#arcto
    • @adius bezier 曲线可以定义圆。这两个命令都适合这种情况。
    • @adius 我从数学的角度理解你的观点,但我认为你看不出用贝塞尔曲线和使用 arc 命令制作的圆的输出有什么不同。在旁注中,OP 不是试图做一个圆,而是用一条曲线连接两条线,因此在这种情况下,贝塞尔曲线命令是合适的。
    • 好的,你是对的,OP 只要求圆角,所以使用贝塞尔曲线本身并没有错,因为它会产生“圆角”。但是你应该用你的语言更精确,因为“贝塞尔曲线可以做圆”是完全错误的。 ?
    【解决方案3】:

    写了一篇文章解释这个https://medium.com/@dphilip/one-side-rounded-rectangle-using-svg-fb31cf318d90

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
      <path
        d="M10,40
           h50
           q5,0 5,5
           v10
           q0,5 -5,5
           h-50
           z
        "
        fill="#4EDFA5"
      >
    <svg>

    【讨论】:

    • 每个属性的详细解释
    【解决方案4】:

    &lt;path&gt; 元素与arc 命令一起使用(http://devdocs.io/svg/attribute/d#arcto)。

    语法:a rx,ry x-axis-rotation large-arc-flag sweep-flag dx,dy

    <svg width="200" height="200" viewBox="0 0 10 10">
      <path d="M0,8 v-3 a5,5 0 0 1 5,-5 h3 v8 z" />
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多