svg gradient

from Red Blob Games

OpenGL supports three-color gradients. There’s a classic triangle drawn with red, green, blue corners, and then within the triangle there’s a smooth gradient. SVG unfortunately does not support three-color gradients. It only has two-color gradients. But someone on on stackoverflow suggested that gradients can work on masks too. With two two-color gradients together, can we make the classic OpenGL three-color triangle?

The first gradient is bottom to top alpha and the second gradient is left to right color. I put blue underneath the red-green triangle. It works!

<svg viewBox="0 0 100 100">
  <defs>
    <!-- see http://stackoverflow.com/questions/21611795/how-to-create-a-transparency-gradient-mask-using-an-svg-filter -->
    <linearGradient id="bottom-to-top-mask" y2="1" x2="0">
      <stop offset="0" stop-color="white" stop-opacity="0.0"/>
      <stop offset="0.9" stop-color="white" stop-opacity="1.0"/>
    </linearGradient>
    <mask id="fade" maskContentUnits="objectBoundingBox">
      <rect width="1" height="1" fill="url(#bottom-to-top-mask)"/>
    </mask>
    <linearGradient id="left-to-right-color" y2="0">
      <stop offset="0.1" stop-color="hsl(120,50%,50%)"/>
      <stop offset="0.9" stop-color="hsl(00,50%,50%)"/>
    </linearGradient>
  </defs>
  <path d="M 50,0 L 100,100 L 0,100 Z" fill="blue"/>
  <path d="M 50,0 L 100,100 L 0,100 Z" fill="url(#left-to-right-color)" mask="url(#fade)"/>
</svg>

This may not be practical but it was fun to try.

Email me at , or tweet to @redblobgames, or post a public comment: