Search code examples
svggradientlinear-gradients

Transforming Linear Gradients Individually For Each Element


Just wanted to double check whether I understand this correctly:

  • If I want to use linear gradients on SVG elements, like <rect>, I need to first put the <linearGradient> inside the <defs> and then reference it either in fill or in style.
  • If I want to transform the gradient for each <rect> individually, I can't do that without defining a <linearGradient> for each individual <rect>, since the gradientTransform property is only allowed on gradient elements.

I'm just confused because ChatGPT told me I can put gradientTransform on my <rect> but MDN says

You can use this attribute with the following SVG elements:

  • <linearGradient>
  • <radialGradient>

So I need individual <linearGradient>s for each <rect>?


Solution

  • Yes, you will need a different gradient for each transformation. But the SVG gradient elements support a bit of templating:

    Most paint server elements accept an href attribute, which can be used to define a compatible paint server element as a template. Attributes defined for the template element are used instead of the initial value if corresponding attributes are not specified on the current element. Furthermore, if the current element does not have any child content other than descriptive elements, than the child content of the template element is cloned to replace it.

    Like this:

    <linearGradient id="grad0" x1="0" y1="0" x2="1" y2="1">
      <stop offset="5%" stop-color="#A8F" />
      <stop offset="95%" stop-color="#FDC" />
    </linearGradient>
    <linearGradient id="grad1" href="grad0" gradientTransform="rotate(30)" />
    <linearGradient id="grad2" href="grad0" gradientTransform="rotate(60)" />