偏移 SVG 填充图案

Bus*_*sti 3 html css svg

是否可以将 svg 元素中的模式偏移一定量?

下面的示例使用嵌入在<g>具有x="70"偏移量的元素中的圆形图案。不幸的是,偏移量只会“切掉”元素的一部分,而不会移动填充图案。

html, body, svg {
    margin: 0;
    width: 100%;
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Pau*_*eau 5

不要偏移矩形,偏移图案。您可以使用xy属性指定模式的原点(偏移)。不管偏移量是正数还是负数,图案仍然会完全填充元素。

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

svg {
    border: solid 1px black;
}
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)

注意:SVG 属性在技术上区分大小写。这种情况正在发生变化,但您应该使用正确的大小写以实现向后兼容性。patternunits应该是patternUnits