Reputation: 6987
I'm trying to create a simple library to draw with SVG on HTML. While the code generates valid HTML that does draw what I want, when I do this programatically, nothing is drawn in the screen. Here's the code that I'm using:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<div id="diagram"></div>
<script type="text/javascript">
function Diagram(div) {
div = document.getElementById(div);
svg = document.createElement("svg");
svg.setAttribute("width", "600");
svg.setAttribute("height", "400");
div.appendChild(svg);
this.diagram = svg;
this.rectangle = function (x, y, width, height) {
rect = document.createElement("rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", width);
rect.setAttribute("height", height);
this.diagram.appendChild(rect);
}
}
var diagram = new Diagram("diagram");
diagram.rectangle(100, 100, 100, 100);
</script>
</body>
</html>
Needless to say, I'm not experienced with JS and I'm using this as an exercise in both learning JS and SVG, but I was unable to understand why my example is not working :-(
Upvotes: 2
Views: 596
Reputation: 318252
When creating SVG elements, you'd use createElementNS
to create elements with a qualified namespace, like SVG elements
document.createElementNS("http://www.w3.org/2000/svg", "svg");
and for certain attributes you'd use setAttributeNS
, but for regular attributes like width and height, setAttribute
should work
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
Upvotes: 2