2017-03-09 70 views
1

這裏是我嘗試建立社交圈:顯示爲什麼從JavaScript創建的svg元素不可見?

,最初硬編碼有
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); 

只有一圈。兩另一個 這是我的腳本添加是不可見的,但它們幾乎identica,如種子DevTools:

They are clearly in the DOM, as seen on screenshot

這裏是鏈接CodePen。也許我搞砸了一些命名空間或風格什麼的?

回答

5

你搞砸了命名空間。你想

var svgns = "http://www.w3.org/2000/svg"; 

沒有/在最後比較你的。

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>

+0

對於那些誰也看不出來區別 - >'/'在最後被刪除 – Weedoze

+0

這是正確的 –