Search code examples
svggradientlinear-gradients

Svg gradient rotation


I've some troubles trying to do two different svg gradient.

The first one should be:

enter image description here

and the second one is similar but it should be rotated by other 90° (so 30 + 90 = 120):

enter image description here:

So, the first one goes from gold to red with stop at 90% and it should be rotated to 30°. The first one goes from gold to red with stop at 90% and it should be rotated to 30°.

<svg width="380" height="760">
  <defs>
    <linearGradient id="myGradient" 
                    gradientTransform="rotate(-30)"
                    >
      <stop offset="0%"  stop-color="gold" />
      <stop offset="90%" stop-color="red" />
    </linearGradient>
    
    <linearGradient id="myGradient2" 
                    gradientTransform="rotate(-120)"
                    >
      <stop offset="0%"  stop-color="gold" />
      <stop offset="90%" stop-color="red" />
    </linearGradient>
  </defs>
  
  <circle cx="190" cy="190" r="190" fill="url('#myGradient')" />
  <circle cx="190" cy="570" r="190" fill="url('#myGradient2')" />
</svg>

It doesn't work. I tried also using the rotation center but nothing seems to work. What am I missing?


Solution

  • Gradients in SVG are described by giving a start and end point. Your gradient is missing the values of the attributes, so the defaults are used: x1="0%" y1="0%" x2="100%" y2="0%". You can state explicit values and leave off the transform:

    <linearGradient id="myGradient" x1="7.3%" y1="25%" x2="93.7%" y2="75%">
    

    If you use a rotation, state its center, because its default is at (0,0), the upper left corner of the bounding box. Note the numbers must be unitless and in the range 0...1:

    <linearGradient id="myGradient" gradientTransform="rotate(-30 0.5 0.5)">
    

    Written like this, the gradient has an implicit default attribute gradientUnits="objectBoundingBox". All numbers are interpreted relative to the bounding box of the element they are used on (the circle). That makes it possible to reuse the same gradient in multiple places, each time going through the colors from start to end.

    If you prefer to use numbers in the same coordinate system as the element they are used on, set gradientUnits="userSpaceOnUse" and use unitless numbers. But that means if you are coloring multiple elements with the same gradient, their start and end point will not adapt - in other words, the gradient continues across the elements.

    <linearGradient id="myGradient" x1="25.45" y1="95" x2="354.55" y2="285"
                    gradientUnits="userSpaceOnUse">
    
    <linearGradient id="myGradient" gradientTransform="rotate(-30 190 190)"
                    gradientUnits="userSpaceOnUse">