SVG pattern 使用(patternUnits、patternContentUnits)

1,002 阅读1分钟

一、简介

  • <pattern>SVG 的一个图案填充标签,可以在 pattern 中定义好图案,然后通过 id 引用来对某个图形进行填充

  • <pattern>width / height 属性默认是根据所填充图形的百分比来确定的。

二、属性

  • pattern 标签另外的两个属性为:

    • patternUnits:默认值为 objectBoundingBox

    • patternContentUnits:默认值为 userSpaceOnUse

      一般用来设置 pattern 内图案的单位大小,如下面实例中的 circle、polygon

  • Units 的取值范围:

    • userSpaceOnUse

      xywidthheight表示的值都是当前用户坐标系统的值。也就是说,这些值没有缩放,都是绝对值。

    • objectBoundingBox(默认值)

      xywidthheight的值都是占外框(包裹 pattern 的元素)的百分比。

三、案例

  • 案例代码

    <svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
        <defs>
          <pattern id="p1" x="0" y="0" width="0.2" height="0.2">
            <circle cx="10" cy="10" r="5" fill="red" />
            <polygon points="30 10 60 50 0 60" fill="green" />
          </pattern>
        </defs>
        <rect x="0" y="0" width="300" height="200" fill="url(#p1)" stroke="blue" />
    </svg>
    
  • 案例效果

    image.png