模式覆盖与 patternUnits 和 patternContentUnits 的组合

填充等效形状时,SVG 模式与 CSS 背景图像的行为明显不同。这可能会让新人对 SVG 产生重大意外。下面是 patternUnits 和 patternContentUnits 的所有可能的组合定义的模式的例子 - 显示了这些设置如何影响补行为。

StackOverflow 文档

<svg width="800px" height="800px">
<defs>
<pattern id="pattern1" x="0" y="0" width="0.2" height="0.2"  patternUnits="objectBoundingBox" patternContentUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="10" fill="blue" />
  </pattern>
  
    <pattern id="pattern2" x="10" y="10" width="20" height="20"  patternUnits="userSpaceOnUse" patternContentUnits="objectBoundingBox">
      <circle cx=".1" cy=".1" r="0.1" fill="blue" />
  </pattern>
  
    <pattern id="pattern3" x="10" y="10" width="20" height="20"  patternUnits="userSpaceOnUse" patternContentUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="10" fill="blue" />
  </pattern>
  
    <pattern id="pattern4" x="0" y="0" width="0.2" height="0.2"  patternUnits="objectBoundingBox" patternContentUnits="objectBoundingBox">
      <circle cx=".1" cy=".1" r="0.1" fill="blue" />
  </pattern>
</defs>

<rect x="10" y="10" width="100" height="100" stroke="black" fill="url(#pattern1)"/>
<rect x="150" y="10" width="200" height="150" stroke="black" fill="url(#pattern1)"/>
  <text x="10" y="200">patternUnits="objectBoundingBox" (20% of shape)</text> 
  <text x="10" y="220">patternContentUnits="userSpaceOnUse" (20px circle) </text>
  <text x="10" y="240" stroke="blue" stroke-width="1">(Units used by default)</text>
  
<rect x="10" y="310" width="100" height="100" stroke="black" fill="url(#pattern3)"/>
<rect x="150" y="310" width="200" height="150" stroke="black" fill="url(#pattern3)"/>
  <text x="10" y="500">patternUnits="userSpaceOnUse" (10px square box)</text> 
  <text x="10" y="520">patternContentUnits="userSpaceOnUse" (20px circle) </text>
  
<rect x="410" y="10" width="100" height="100" stroke="black" fill="url(#pattern2)"/>
<rect x="550" y="10" width="200" height="150" stroke="black" fill="url(#pattern2)"/>
  <text x="410" y="200">patternUnits="userSpaceOnUse" (10px square box)</text> 
  <text x="410" y="220">patternContentUnits="objectBoundingBox"(radius="10%") </text>
  
<rect x="410" y="310" width="100" height="100" stroke="black" fill="url(#pattern4)"/>
<rect x="550" y="310" width="200" height="150" stroke="black" fill="url(#pattern4)"/>
  <text x="410" y="500">patternUnits="objectBoundingBox" (20% of shape)</text> 
  <text x="410" y="520">patternContentUnits="objectBoundingBox"(radius="10%")  </text>
  
</svg>