Mastering SVG: The Paint-Order Attribute Explained

You would think that in this age of generative AI, that going deep into a subject is no longer en vogue. I mean, when you’ve got copilot and ChatGPT at your finger tips, aren’t you just supposed to prompt your way to coding nirvana?

Well, us humans still have something to offer to the intellectual pursuits of programming. I’m going to explore one such case in point. I will use the rendering of .svg as a backdrop. This is kinda technical, so if you’re not into that, you might want to avert your eyes now.

Let’s start with a picture.

And the .svg code that goes with it.

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200">

  <linearGradient id="g" x1="0" y1="0" x2="0" y2="1">

    <stop stop-color="#888" />

    <stop stop-color="#ccc" offset="1" />

  </linearGradient>

  <rect width="400" height="200" fill="url(#g)" />

  <g

    fill="crimson"

    stroke="white"

    stroke-width="6"

    stroke-linejoin="round"

    text-anchor="middle"

    font-family="sans-serif"

    font-size="50px"

    font-weight="bold">

    <text x="200" y="75" stroke-width="1">stroke over</text>

    <text x="200" y="150" paint-order="stroke fill" id="stroke-under">

      stroke under

    </text>

  </g>

</svg>

What I’m focusing on here is the ‘paint-order’. On the second text element, it has a value of “stroke fill”. The paint-order attribute tells the rendering engine which order of operations to perform. Whenever something is being rendered, whether a standard shape such as a square, circle, or polygon, there is an order to things. The normal order is; fill, stroke, markers. That is, fill the shape first, then draw the outline, then draw any markers if there are any. The paint-order allows you to change that ordering, to obtain different effects. The default for shapes is “fill stroke markers”.

In the above image, you can see the top text is doing the ‘normal’ thing, and the fill occurs, and a stroke of thickness ‘1’ is drawn on top of that. The second line of text changes the paint-order to be “stroke fill” and changes the stroke-width to be “6”, so it’s a thicker line. We want that outline to appear behind the text, so we still get a nice clean text, on top of a puffy looking outline.

Besides general stylized occasions, this work out well when drawing text on a map, for instance.

Next
Next

Let’s Talk SVG Again