Search code examples
jquerycsssvgdimple.js

Generating an SVG rectangle with dashed fill lines


I have a rectangle made with dimpleJS and need the box filled with dashed lines instead of a solid color. Is this possible using svg, css and/or jquery? The rectangle is below.

<rect id="dimple-not-working-on-an-associate-s-degree-2008-not-working-on-an-associate-s-degree---" class="dimple-series-0 dimple-bar dimple-not-working-on-an-associate-s-degree dimple-2008 dimple-not-working-on-an-associate-s-degree dimple-custom-series-bar dimple-custom-format-1" x="183.5" y="128.4" width="18" height="141.6" opacity="0.8" style="fill: rgb(92, 186, 230); stroke: rgb(77, 156, 192);" fill="#5cbae6" stroke="rgb(77, 156, 192)"></rect>

Solution

  • As Robert mentions in the comments, what you need to do is using a pattern to fill the rectangle. The steps are easy:

    • Define a pattern in the SVG
    • Inside the pattern, "draw" whatever you want to be the pattern. For example, you want dashed lines, so you would do a line that occupies only part of the pattern, so when it is repeated it will look dashed.
    • Set the attribute patternUnits to "userSpaceOnUse"so the pattern will occupy the whole element in which it is applied (as it would do with a background-repeat).
    • Apply the pattern in the fill attribute by referencing its id (e.g. fill="url(#pattern-id)")

    Here you can see a demo working:

    <svg width="100" height="100" viewBox="0 0 100 100">
      <defs>
        <pattern id="lines" height="10" width="10" patternUnits="userSpaceOnUse">
          <line x1="0" y1="4" x2="5" y2="4" stroke-width="2" stroke="black"/>
        </pattern>
      </defs>
      <rect x="10" y="10" width="80" height="80" fill="url(#lines)" />
    </svg>