0

My code adds polylines to a SVG, but these are not rendered.

But if I open the inspector (F12 on Chrome), find them in source, right click on them, edit as HTML, add a space and press enter, they get rendered!

What am I missing here?

function drawLine(x1, y1, x2, y2) {
    var line = document.createElement("polyline");
    line.style.cssText = "fill:none;stroke:black;stroke-width:2";

    var linePoints = `${x1},${y1} ${x2},${y2}`;
    line.setAttribute('points', linePoints);

    window.linesContainer.appendChild(line);
}

enter image description here

Edit1:

Something interesting is that initially the polyline seems to have 0pxw and 0pxh

enter image description here

While after modifying it, it gets a size:

enter image description here

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36

1 Answers1

3

For non-HTML elements (in this case SVG), you should use createElementNS, though you shouldn't use setAttributeNS with the SVG namespace

So the new code is:

var svg_NS = 'http://www.w3.org/2000/svg';
var svg = document.getElementById('svg');
function drawLine(x1, y1, x2, y2) {
    var line = document.createElementNS(svg_NS, "polyline");
    line.style.cssText = "fill:none;stroke:black;stroke-width:2";
    
    var linePoints = `${x1},${y1} ${x2},${y2}`;
    line.setAttribute('points', linePoints);
    
    window.linesContainer.appendChild(line);
}
    
drawLine(0,0,200,200)
<svg id="linesContainer"></svg>

See more:

https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course https://stackoverflow.com/a/6701928/6184972

Steve
  • 10,435
  • 15
  • 21