Reputation: 8067
Here is how I try to create circles:
var svgns = "http://www.w3.org/2000/svg/";
var circle = function(x, y) {
this.x = x;
this.y = y;
this.element = document.createElementNS(
svgns, "circle"
);
this.element.setAttributeNS(null, "cx", x);
this.element.setAttributeNS(null, "cy", y);
this.element.setAttributeNS(null, "r", CIRCLE_RADIUS);
this.element.setAttributeNS(null, "fill", randomColor());
svg.appendChild(this.element);
}
circle(100, 100);
Only circle that was hardcoded there initially is displayed. Two another, which are added by my script are not visible, but they are almost identica, as seed in DevTools:
Here is link to CodePen. Maybe I messed up some namespaces or styles or something?
Upvotes: 1
Views: 173
Reputation: 124029
You messed up the namespace. You want
var svgns = "http://www.w3.org/2000/svg";
No / at the end compared to yours.
var CIRCLE_RADIUS = 10;
var svg = document.getElementById('canvas');
var randomColor = function() {
return ['red', 'green', 'blue'][Math.floor(Math.random() * 3)];
}
var svgns = "http://www.w3.org/2000/svg";
var circle = function(x, y) {
this.x = x;
this.y = y;
this.element = document.createElementNS(
svgns, "circle"
);
this.element.setAttributeNS(null, "cx", x);
this.element.setAttributeNS(null, "cy", y);
this.element.setAttributeNS(null, "r", CIRCLE_RADIUS);
this.element.setAttributeNS(null, "fill", randomColor());
svg.appendChild(this.element);
}
circle(100, 100);
circle(10, 10)
<svg width="800" height="800" id="canvas">
<circle cx="60" cy="10" r="10" fill="gray"/>
</svg>
Upvotes: 5