Tony the Pony
Tony the Pony

Reputation: 41367

Equivalent of "background-repeat: round" in SVG?

CSS has a handy option for background images in HTML elements: If I have a pattern that is 20 pixels high, but my HTML element has a height that isn't evenly divisible by 20 (e.g. 150px or 35px), background-repeat: round will tile the pattern to make it appear seamless, stetching/squeezing the tiles as needed.

Is there an equivalent styling option for patterns within an SVG element? For example:

<defs>
    <pattern id="myPattern" width="200" height="100" patternUnits="userSpaceOnUse">
        ... some pattern ...
    </pattern>
</defs>

<rect width="200" height="230" fill="#myPattern"/>

I'd like to have two whole repetitions of the pattern in my rectangle (stretched to 115px each), not two whole repetitions and a partial third.

EDIT

The solution by ccprog (below) works fine for this particular example. However, it requires the pattern to define how many times it will be repeated. I'm still holding out hope for a general solution for cases where the elements using the pattern are of different heights (and hence will require different numbers of pattern repetitions).

Upvotes: 2

Views: 137

Answers (1)

ccprog
ccprog

Reputation: 21821

You can set a viewBox for patterns and define pattern units in terms of the object bounding box:

<defs>
    <pattern id="myPattern" width="50%" height="50%"
             viewBox="0 0 200 100" preserveAspectRatio="none"
             patternUnits="objectBoundingBox">
        ... some pattern ...
    </pattern>
</defs>

<rect width="200" height="230" fill="#myPattern"/>

It's not completely equivalent to CSS round, as you implicitely give the absolute number of repetitions with the width/height attributes, no matter how large the filled area is.

Upvotes: 1

Related Questions