Search code examples
javascriptsvglinear-gradients

SVG Linear gradient hard stop


I am trying to achieve a hard stop in linear gradient as this.

I am trying to achieve this with javascript as following

const color = ["red", "green", "blue", "magenta"];
const svgns = 'http://www.w3.org/2000/svg';
const svgVan = document.querySelector('svg');

const lg = document.createElementNS(svgns, 'linearGradient');
lg.setAttribute('id', 'linear');
lg.setAttribute('x1', '0%');
lg.setAttribute('y1', '0%');
lg.setAttribute('x2', '100%');
lg.setAttribute('y2', '0%');
svgVan.appendChild(lg);

color.forEach(
    (a, i) => {
        const stop1 = document.createElementNS(svgns, 'stop');
        stop1.setAttribute('offset', i / color.length);
        stop1.setAttribute('stop-color', a);
        lg.appendChild(stop1)

        const stop2 = document.createElementNS('svgns', 'stop');
        stop2.setAttribute('offset', (i + 1) / color.length);
        stop2.setAttribute('stop-color', a);
        lg.appendChild(stop2)
    }
)

const rect = document.createElementNS(svgns, 'rect')
rect.setAttribute('x', '100');
rect.setAttribute('y', '100');
rect.setAttribute('width', '600');
rect.setAttribute('height', '200');
rect.setAttribute('fill', 'url(#linear)')
rect.setAttribute('stroke', 'black');
svgVan.appendChild(rect);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="container" class="svg-container"></div>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 720">  

    </svg>  
    <script src="index2.js"></script>
</body>

</html>

The browser is generating the same mark-up as codepen but the end result is not the same. Even though the mark-up is identical

S1


Solution

  • const stop2 = document.createElementNS('svgns', 'stop');
    

    should be

    const stop2 = document.createElementNS(svgns, 'stop');
    

    See demo: https://codepen.io/smpao1/pen/vYdaWMW

    The namespace is set to the namespace 'svgns', which will not get interpreted as a valid svg element, and is thus ignored.