Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading