jeudi 21 novembre 2019

How to Apply Masked SVG Patterns using Coord System of ObjectBoundingBox

I am writing inline SVG code for a data visualization and I'm trying to apply a <mask> which I filled with a <pattern> to multiple SVG <rect> elements.

I can't find a combination of patternUnits, patternContentUnits, maskUnits and maskContentUnits that makes the mask filling 100% of each rect it gets applied to without stretching the pattern. Is it even possible? The pattern itself is not that complicated and should look like this: correct pattern dimensions applied

Due to performance optimization I wan't the <defs> tag to live in a separate svg at root level of my component.

#my-defs {
  position: absolute;
  top: -1000px;
  left: -1000px;
}

#my-svg {
  width: 200px;
  height: 3em;
}

#my-svg rect {
  width: 100%;
  height: 80%;
}
<svg id="my-defs">
  <defs>
    <pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4">
      <path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" />
    </pattern>
    <mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="objectBoundingBox">
      <rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="1" height="1" />
    </mask>
  </defs>
</svg>

<svg id="my-svg">
  <rect fill="steelblue" mask="url(#diagonal-hatch-mask)" />
</svg>

Aucun commentaire:

Enregistrer un commentaire