是SVG的一个图案填充标签,可以在pattern中定义好图案,然后通过id引用来对某个图形进行填充,的width/height属性默认是根据所填充图形的百分比来确定的。

    1. <svg width="1000" height="1000">
    2. <defs>
    3. <pattern id="grid" x="100" y="100" width="0.2" height="0.2" patternUnits="objextBoundingBox">
    4. <circle cx="10" cy="10" r="5" fill="red"></circle>
    5. <polygon points="30 10 60 50 0 50" fill="green"></polygon>
    6. </pattern>
    7. </defs>
    8. <rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect>
    9. </svg>

    SVG中<pattern>标签使用 - 图1
    <defs>标签内定义图案,<pattern>元素中的内容直到引用的时候才会显示。
    设置id为”grid”,x、y值的改变决定图案的位置,宽度、高度默认为pattern图案占填充图形的百分比。
    内部定义了两个图形,

    将patternUnits值默认为objextBoundingBox,指pattern大小是占rect所填充图形的大小
    在外部定义了一个矩形,在矩形的fill中引用id名。
    将填充图形rect的width改为200时:

    1. <rect x="100" y="100" width="200" height="200" fill="url(#grid)" stroke="blue"></rect>

    图案的个数并没有改变,的width/height属性默认是根据所填充图形的百分比来确定的。
    将patternUnits设置为userSpaceOnUse时,效果如下:

    1. <svg width="1000" height="1000">
    2. <defs>
    3. <pattern id="grid" x="100" y="100" width="80" height="60" patternUnits="userSpaceOnUse">
    4. <!-- <path stroke="#f0f0f0" fill="none" d="M0,0H20V20"></path> -->
    5. <circle cx="10" cy="10" r="5" fill="red"></circle>
    6. <polygon points="30 10 60 50 0 50" fill="green"></polygon>
    7. </pattern>
    8. </defs>
    9. <rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect>
    10. </svg>

    pattern标签另外的两个属性为patternUnits和patternContentUnits,两个属性值一样,但patternUnits默认值为objectBoundingBox,而patternContentUnits默认值为userSpaceOnUse,patternContentUnits用来设置pattern内图案的单位大小,如上面实例中的circle、polygon。

    userSpaceOnUsexywidthheight表示的值都是当前用户坐标系统的值。也就是说,这些值没有缩放,都是绝对值。比如上面的例子中:将pattern中width、height设为80、60时,相当于width、height为0.2。

    objectBoundingBox(默认值)xywidthheight的值都是占外框(包裹pattern的元素)的百分比。比如上面的例子中:将pattern中width、height设为1时,相当于pattern内的图案占rect的百分百,上面实例设置为0.2,相当于占rect的20%。