簡體   English   中英

為什么從JavaScript創建的svg元素不可見?

[英]Why svg elements created from JavaScript are not visible?

這是我嘗試創建圈子的方法:

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);

僅顯示最初在此處進行硬編碼的圓。 我的腳本添加的另外兩個是不可見的,但它們幾乎是相同的,就像DevTools中的種子一樣:

如屏幕截圖所示,它們顯然在DOM中

這是CodePen的鏈接。 也許我弄亂了一些名稱空間或樣式之類的東西?

您弄亂了名稱空間。 你要

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM