Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!