Search code examples
svg

Simple fill pattern in svg : diagonal hatching


How would I fill an SVG shape, not with a single colour, an image or a gradient, but with a hatching pattern, diagonal if possible.

It's been 2 hours and I've found nothing (at least after 2005).

I figure a possible hack would be a hatched PNG that would serve as fill, but that is not ideal.


Solution

  • I did not find anything for diagonal hatching on the internet either, so I'll share my solution here:

    <pattern id="diagonalHatch" patternUnits="userSpaceOnUse" width="4" height="4">
      <path d="M-1,1 l2,-2
               M0,4 l4,-4
               M3,5 l2,-2" 
            style="stroke:black; stroke-width:1" />
    </pattern>
    

    (note the lower case "l" in the path expression)

    The above creates a hatch with diagonal lines from the lower left to the upper right that are 4 pixels apart. Besides the diagonal line (M0,4 l4,-4) you also have to stroke the upper left and the lower right edges of the pattern area, since the line will otherwise be "constricted" due to clipping where it intersects the edges of the square.

    Example of a pattern after applying the above steps, it shows how the pattern it titled to make the end product

    To fill a rectangle with this pattern, do:

    <rect x="0" y="0" width="100%" height="100%" fill="url(#diagonalHatch)"/>