Busti
Busti

Reputation: 5614

Offset an SVG fill pattern

Is it possible to offset the pattern in an svg element by a certain amount?

The example below uses a pattern of circles that is embedded in a <g> element that has an x="70" offset. Unfortunately the offset only 'cuts' away a part of the element without moving the fill pattern.

html, body, svg {
    margin: 0;
    width: 100%;
    height: 100%;
}
<svg class="gFlow" id="main" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <pattern height="64" id="grid" patternunits="userSpaceOnUse" width="64">
            <circle cx="32" cy="32" fill="orange" r="5"></circle>
        </pattern>
    </defs>
    <rect fill="url(#grid)" height="100%" width="100%" x="70"></rect>
</svg>

Upvotes: 3

Views: 5383

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101918

Don't offset the rectangle, offset the pattern. You can specify the origin (offset) of a pattern using the x and y attributes. It doesn't matter if the offset is positive or negative, the pattern will still fill the element completely.

html, body, svg {
    margin: 0;
    width: 100%;
    height: 100%;
}

svg {
    border: solid 1px black;
}
<!-- Pattern with no offset -->
<svg class="gFlow" id="main" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <pattern height="64" id="grid" patternUnits="userSpaceOnUse" width="64">
            <circle cx="32" cy="32" fill="orange" r="5"></circle>
        </pattern>
    </defs>
    <rect fill="url(#grid)" height="100%" width="100%"></rect>
</svg>

<!-- Pattern moved right by half the pattern width (32) -->
<svg class="gFlow" id="main" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <pattern height="64" id="grid" patternUnits="userSpaceOnUse" width="64"
                 x="32" y="0">
            <circle cx="32" cy="32" fill="orange" r="5"></circle>
        </pattern>
    </defs>
    <rect fill="url(#grid)" height="100%" width="100%"></rect>
</svg>

Note: SVG attributes are technically case sensitive. That's changing, but you should use the correct case for backwards compatibility. patternunits should be patternUnits.

Upvotes: 6

Related Questions