Reputation: 684
I want to apply a pattern to a few svg elements, the pattern should apply from the (0,0) point for each element.
First I try code like this
<svg width="400" height="400">
<defs>
<pattern id="pattern1"
x="0" y="0" width="25" height="25"
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);" />
<rect x="110" y="17" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
<rect x="210" y="0" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
<rect x="0" y="110" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
</svg>
The issue in this example is that the pattern for each element starts from the (0,0) point of the svg document not of each element.
Ok, lets try (setting the patternUnits="objectBoundingBox"
attribute to the pattern definition so that the coordinate system for the pattern starts from the (0,0) point of each element)[https://jsfiddle.net/gwrgd1wf/1/]
The Coordinate system start point is changed as I want it, but the pattern has stopped tiling and the width
and height
attribute of pattern stop working properly. You can see I set height="2"
, but it does not change the height of the pattern.
So my question is how to properly use the patternUnits="objectBoundingBox"
attribute?
Upvotes: 4
Views: 4302
Reputation: 124219
In objectBoundingBox units 1 unit is the size of the shape so if you write 2 that means the pattern is 2 times the size of the shape so 1/2 the pattern fills the shape and you get no tiling.
If you want tiling you'll need to make the pattern smaller than the shape e.g. with 0.2 you'll get 5 circles displayed. E.g.
<svg width="400" height="400">
<defs>
<pattern id="pattern1"
x="0" y="0" width="0.2" height="0.2"
patternUnits="objectBoundingBox"
>
<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);" />
<rect x="110" y="17" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
<rect x="210" y="0" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
<rect x="0" y="110" width="100" height="100"
style="stroke: #000000; fill: url(#pattern1);" />
</svg>
Upvotes: 4