<svg width="1000" height="1000">
<defs>
<pattern id="grid" x="100" y="100" width="0.2" height="0.2" patternUnits="objextBoundingBox">
<circle cx="10" cy="10" r="5" fill="red"></circle>
<polygon points="30 10 60 50 0 50" fill="green"></polygon>
</pattern>
</defs>
<rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect>
</svg>
在<defs>
标签内定义图案,<pattern>
元素中的内容直到引用的时候才会显示。
在
将patternUnits值默认为objextBoundingBox,指pattern大小是占rect所填充图形的大小
在外部定义了一个
将填充图形rect的width改为200时:
<rect x="100" y="100" width="200" height="200" fill="url(#grid)" stroke="blue"></rect>
图案的个数并没有改变,
将patternUnits设置为userSpaceOnUse时,效果如下:
<svg width="1000" height="1000">
<defs>
<pattern id="grid" x="100" y="100" width="80" height="60" patternUnits="userSpaceOnUse">
<!-- <path stroke="#f0f0f0" fill="none" d="M0,0H20V20"></path> -->
<circle cx="10" cy="10" r="5" fill="red"></circle>
<polygon points="30 10 60 50 0 50" fill="green"></polygon>
</pattern>
</defs>
<rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect>
</svg>
pattern标签另外的两个属性为patternUnits和patternContentUnits,两个属性值一样,但patternUnits默认值为objectBoundingBox,而patternContentUnits默认值为userSpaceOnUse,patternContentUnits用来设置pattern内图案的单位大小,如上面实例中的circle、polygon。
userSpaceOnUse:x
、y
、width
和height
表示的值都是当前用户坐标系统的值。也就是说,这些值没有缩放,都是绝对值。比如上面的例子中:将pattern中width、height设为80、60时
,相当于width、height为0.2。
objectBoundingBox(默认值):x
、y
、width
和height
的值都是占外框(包裹pattern的元素)的百分比。比如上面的例子中:将pattern中width、height设为1时
,相当于pattern内的图案占rect的百分百,上面实例设置为0.2,相当于占rect的20%。