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.
I did not find anything for diagonal hatching on the internet either, so I'll share my solution here:
(note the lower case "l" in the path expression)
The above creates a hatch that with diagonal lines from the lower left to the upper right that are 4 pixels apart. Beside 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.To fill a rectangle with this pattern, do:
One problem with drawing a diagonal line within a pattern is that when the pattern is tiled the lines won't always line up - especially at high zooms. (It depends on the SVG rendering engine you happen to be using). @Ingo's answer above attempts to resolve this by drawing in the triangles at the top-left and bottom-right corners - but again, using some rendering engines and high zooms, it doesn't always look best - and sometimes the line ends up looking a bit like a string of sausages.
Another approach is to draw a horizontal line in the pattern and rotate the pattern, e.g.
This is a solution for diagonal lines using circle in pattern. You can change angle as per your requirements.
Use the patternTransform attribute to rotate a vertical (or horizontal) line segment. This method tiles seamlessly and uses the simplest possible path. The pattern
width
attribute controls how close parallel hatches are.These two resources are very helpful: https://bocoup.com/weblog/using-svg-patterns-as-fills https://github.com/iros/patternfills/blob/master/public/patterns.css
For example:
This code from http://bl.ocks.org/jfsiii/7772281 seems very clean and reusable: