如何使用objectBoundingBox坐标系将svg模式应用于不同的矩形并保持纵横比?

时间:2015-08-04 09:03:32

标签: svg

即。在此代码中,图案应用了瓷砖之间的间隙或重叠。

<svg width="400" height="400">
<defs>
  <pattern id="pattern1" 
      x="0" y="0" width="0.1" height="0.2"
      patternUnits="objectBoundingBox"
  >
      <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />
  </pattern>
</defs>

<rect x="10" y="10" width="170" height="100"
    style="stroke: #000000; fill: url(#pattern1);" /> 
    
<rect x="10" y="110" width="235" height="100"
    style="stroke: #000000; fill: url(#pattern1);" />     
</svg>

如何将瓷砖并排放置,最后一块不适合矩形的瓷砖会被切片?

1 个答案:

答案 0 :(得分:3)

您无法使用objectBoundingBox单位执行所需操作。您需要使用patternUnits="userSpaceOnUse"

<svg width="400" height="400">
<defs>
  <pattern id="pattern1" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />
  </pattern>
</defs>

<rect x="10" y="10" width="170" height="100"
    style="stroke: #000000; fill: url(#pattern1);" /> 
    
<rect x="10" y="110" width="235" height="100"
    style="stroke: #000000; fill: url(#pattern1);" />     
</svg>

但是,正如您所看到的,默认模式原点位于SVG文档的原点(左上角)。要更改它以使图案与矩形对齐,您需要在原点处定义矩形并使用transform将它们移动到位。

<svg width="400" height="400">
<defs>
  <pattern id="pattern1" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />
  </pattern>
</defs>

<rect x="0" y="0" width="170" height="100" transform="translate(10,10)"
    style="stroke: #000000; fill: url(#pattern1);" /> 
    
<rect x="0" y="0" width="235" height="100" transform="translate(10,110)"
    style="stroke: #000000; fill: url(#pattern1);" />     
</svg>