好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SVG进阶 | SVG填充模式

SVG填充模式 是指使用某种图像作为模式来填充 SVG 图形。这种模式可以是SVG图形或位图。

其实SVG填充模式所做的事情就是使用某种图案反复的填充整个SVG图形,就像PhotoShop中的“图案图章工具”所做的那样。

填充模式的例子

下面是一个简单的SVG填充模式的例子:

<defs>
  <pattern id="pattern1"
           x="10" y="10" width="20" height="20"
           patternUnits="userSpaceOnUse" >

      <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />

  </pattern>
</defs>

<rect x="10" y="10" width="100" height="100"
    style="stroke: #000000; fill: url(#pattern1);" />

在上面的代码中, <pattern> 元素被定义在 <defs> 元素中。在 <pattern> 元素元素中包含一个 <circle> 元素,这个圆形将被用于作为填充模式。

然后,在下面的 <rect> 元素中, style 属性的 fill  CSS属性指向了 <pattern> 元素。这意味着要使用这个模式来填充矩形。

上面的代码得到的结果如下:

image.png

现在,圆形在矩形内部从左向右,从上向下反复不断的填充矩形。

填充模式的X,Y和width,height属性

<pattern> 元素的 X 和 Y 属性指定填充模式的开始位置。

<pattern> 元素的 width 和 height 属性指定填充模式的宽度和高度。

下面的例子和前面的例子类似,但是 X 和 Y 属性设置为(0,0)。

<defs>
  <pattern id="pattern2"
           x="0" y="0" width="20" height="20"
           patternUnits="userSpaceOnUse" >
      <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />

  </pattern>
</defs>

<rect x="10" y="10" width="100" height="100"
    style="stroke: #000000; fill: url(#pattern1);" />

如果将 height 属性也设置为25,那么会得到下面的结果:

image.png

如果将上面的例子中的 x 和 y 属性都设置为10,那么模式会从一个整圆开始,结果如下:

image.png

嵌套填充模式

SVG的填充模式也可以进行嵌套,这样会在一个填充模式的内部使用另一个填充模式。来看下面的例子,在一个矩形内部使用圆形的填充模式,而圆形填充模式的内部又嵌套一个矩形的填充模式。

<defs>
    <pattern id="innerPattern"
             x="3" y="3" width="9" height="9"
             patternUnits="userSpaceOnUse"
            >
        <rect x="0" y="0" width="6" height="6"
              style="stroke: none; fill: #ff0000;" />

    </pattern>

    <pattern id="outerPattern"
             x="12" y="12" width="25" height="25"
             patternUnits="userSpaceOnUse"
            >

        <circle cx="10" cy="10" r="10"
            style="stroke: #0000ff; fill: url(#innerPattern)" />

    </pattern>
</defs>

<rect x="10" y="10" width="100" height="100"
      style="stroke: #000000; fill: url(#outerPattern);" />

上面代码的返回结果如下:

image.png

填充模式的转换

你可以使用标准的SVG转换函数来对SVG填充模式进行转换。可以通过 patternTransform 属性来实现对填充模式的转换。下面是一个转换SVG填充模式的例子:

<defs>
  <pattern id="transformedPattern"
         x="10" y="10" width="20" height="20"
         patternUnits="userSpaceOnUse"
         patternTransform="rotate(35)"
        >

    <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />

  </pattern>
</defs>

<rect x="10" y="10" width="100" height="100"
      style="stroke: #000000;
             fill: url(#transformedPattern);" />

在这个例子中定义了一个简单的模式,并在将它填充到矩形之前旋转35度。得到的结果如下所示:

image.png

查看更多关于SVG进阶 | SVG填充模式的详细内容...

  阅读:73次