Reputation: 261
I've tried so much. Nothing works. Anybody help me?
Thanks.
var svg = document.createElement("svg");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
var line = document.createElement("line");
line.setAttribute("x1", "0");
line.setAttribute("y1", "0");
line.setAttribute("x2", "100");
line.setAttribute("y2", "100");
line.setAttribute("stroke", "black");
line.setAttribute("stroke-width", "4px");
svg.appendChild(line);
document.body.appendChild(svg);
Upvotes: 0
Views: 69
Reputation: 48600
The following should work. Create the element and apply the styles using:
This makes it so that the svg and it's inner shapes will be created within the scope (hence – namespace) of the SVG and not the HTML document.
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttributeNS(null, 'width', '100%');
svg.setAttributeNS(null, 'height', '100%');
var line = document.createElementNS(svgns, "line");
line.setAttributeNS(null, 'x1', 0);
line.setAttributeNS(null, 'y1', 0);
line.setAttributeNS(null, 'x2', 100);
line.setAttributeNS(null, 'y2', 100);
line.setAttributeNS(null, 'stroke', 'black');
line.setAttributeNS(null, 'stroke-width', 4);
svg.appendChild(line);
document.body.appendChild(svg);
Simpler, but still works:
var svgns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgns, "svg");
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
var line = document.createElementNS(svgns, "line");
line.setAttribute('x1', 0);
line.setAttribute('y1', 0);
line.setAttribute('x2', 100);
line.setAttribute('y2', 100);
line.setAttribute('stroke', 'black');
line.setAttribute('stroke-width', 4);
svg.appendChild(line);
document.body.appendChild(svg);
Upvotes: 1