0

I have this gradient that uses userSpaceOnUse.

<svg height="400px" width="800px" viewBox="0 0 800 400" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <linearGradient id="grad1" x1="0" y1="0" x2="800" y2="400" gradientUnits="userSpaceOnUse">
            <stop offset="0%" style="stop-color:green;stop-opacity:1" />
            <stop offset="50%" style="stop-color:black;stop-opacity:1" />
            <stop offset="100%" style="stop-color:red;stop-opacity:1" />
        </linearGradient>
    </defs>
    <rect x="0" y="0" width="800" height="400" fill="url(#grad1)"/>
</svg>

I want to rewrite it to use objectBoundingBox but be rendered the same. How can I do this?

I imagine the rewritten SVG would be close to:

<svg height="400px" width="800px" viewBox="0 0 800 400" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <linearGradient id="grad1" x1="0" y1="0" x2="1" y2="1" gradientUnits="objectBoundingBox">
            <stop offset="0%" style="stop-color:green;stop-opacity:1" />
            <stop offset="50%" style="stop-color:black;stop-opacity:1" />
            <stop offset="100%" style="stop-color:red;stop-opacity:1" />
        </linearGradient>
    </defs>
    <rect x="0" y="0" width="800" height="400" fill="url(#grad1)"/>
</svg>

This answer (https://stackoverflow.com/a/50624704/1283776) indicates that I need to use a transform, but I haven't been successful in found a solution.

user1283776
  • 19,640
  • 49
  • 136
  • 276

1 Answers1

0

<!-- https://stackoverflow.com/questions/22214999/svg-linear-gradient-independent-of-the-shape-coordinates -->

<svg height="400px" width="800px" viewBox="0 0 800 400" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <linearGradient id="grad1" x1="0" y1="0" x2="1" y2="0.5" gradientUnits="objectBoundingBox" gradientTransform="scale(1, 2)">
            <stop offset="0%" style="stop-color:green;stop-opacity:1" />
            <stop offset="50%" style="stop-color:black;stop-opacity:1" />
            <stop offset="100%" style="stop-color:red;stop-opacity:1" />
        </linearGradient>
    </defs>
    <rect x="0" y="0" width="800" height="400" fill="url(#grad1)"/>
</svg>
user1283776
  • 19,640
  • 49
  • 136
  • 276