2017-03-09 10 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です:

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

を除去して、これは正しいです –

関連する問題