Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offset an SVG fill pattern

Tags:

html

css

svg

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>
like image 860
Busti Avatar asked Jun 24 '26 17:06

Busti


1 Answers

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.

like image 88
Paul LeBeau Avatar answered Jun 27 '26 07:06

Paul LeBeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!