填充 SVG 路径的内部

问题描述 投票:0回答:1

我正在尝试使用以下 HTML 代码填充 SVG 中路径元素的内部:

我在SO上看过几篇相关的帖子,但我发现它们难以理解并且没有帮助。我需要做什么才能用颜色填充路径元素的内部?

<h2>Start of arrow</h2>

  <svg width="450" height="400" xmlns="http://www.w3.org/2000/svg">
    <g id="arrow" stroke="red" stroke-width="3" stroke-linecap="round" fill="green">
      <path d="M100 298 Q 300 306 400 290"/>
      <path d="M100 315 Q 300 305 400 315"/>
      <path d="M100 298 Q 112 306 100 315"/>
    </g>
  </svg>

html svg
1个回答
0
投票

TL;DR:您需要合理的绘图/坐标顺序(GUI 或标记)

绘制填充路径的一种方法是将路径数据抽象为多边形并以合适的顺序对命令坐标进行排序:

(重新排序路径命令要求您的路径命令使用绝对坐标 - 例外情况是仅描述 x 或 y 坐标的

H
V
命令)

  1. 连接路径数据 – 由
    d
    属性指定
  2. 到多边形的路径命令(删除
    M
    之后的所有命令标记,如
    Q
  3. 删除多余的相邻命令坐标
  4. 添加
    Q
    命令标记将某些顶点解释为二次贝塞尔控制点(定义曲率)

body {
  font-family: sans-serif;
}

svg {
  border: 1px solid #ccc;
}
<h3>1. Concatenated path commands to polygon – gibberish :(</h3>
<p>Strip Command type letters. Third path should become 2nd command. Whitespace agnostic. </p>
<svg viewBox="0 200 450 200">
  <path stroke="red" stroke-width="3" stroke-linecap="round" fill="none" d="
             M 100,298  300,306  400,290
             100,315  300,305  400,315
             100,298  112,306  100,315" />
</svg>

<h3>2. Path commands to polygon – sort points by logical drawing order (top-right to bottom-right)</h3>
<svg viewBox="0 200 450 200">
  <!-- 
    1. path1: quadratic command end point to start/moveTo 
    2. path1: Moveto to quadratic final point
    3. path3: to 2nd segment
    4. path2: to 3rd segment
    -->
  <path stroke="red" stroke-width="3" stroke-linecap="round" fill="none" d="
             M 
             400,290  300,306  100,298
             100,298  112,306  100,315
             100,315  300,305  400,315
             " />
</svg>

<h3>3. Path commands to polygon – remove redundant adjacent coordinates</h3>
<svg viewBox="0 200 450 200">
  <path stroke="red" stroke-width="3" stroke-linecap="round" fill="none" d="
             M 400,290  300,306  100,298
             112,306  100,315
             300,305  400,315
             " />
</svg>


<h3>4. Path polygon to quadratic Béziercontrol points</h3>
<svg viewBox="0 200 450 200">
  <path stroke="red" stroke-width="3" stroke-linecap="round" fill="red" d="
             M 
             400,290  Q 300,306  100,298
             Q 112,306  100,315
             Q 300,305  400,315
             z
             " />
</svg>

SVG 标记可读性:

  • SVG 路径数据属性与空白无关 - 因此您可以轻松添加换行符或制表符缩进以提高开发的可读性
  • 如果有助于提高可读性,您还可以使用不同的分隔符(如
    ,
    )对 x/y 坐标对进行分组

GUI(图形应用程序)与 SVG 标记

  • 像 Inkscape 这样的 GUI 驱动的矢量编辑器的基本知识非常有用 - 除了数据驱动的动态生成的可视化(图表、图形等)之外,其他复杂的矢量图形(字体、图标、徽标等)通常是使用图形应用程序,然后导出到 SVG(并按代码进行优化/微调)。
  • SVG 路径数据命令的基本知识也很有帮助 – 但是:如果您可以使用 GUI 更快、更准确地完成任务 – 那就完美了!
  • 如果您需要编写用于动态SVG创建(例如前面提到的数据可视化)解析或操作的库/脚本,则主要需要更深刻的理解

进一步阅读

© www.soinside.com 2019 - 2024. All rights reserved.