2014-01-25 25 views
0

我正在計算使用Javascript在svg元素內的pathcircle的值。我可以將正確的HTML代碼注入HTML頁面,但不繪製circle/svg。HTML SVG不繪製(適用於其他頁面)

這就是被Javascript

<svg> 
    <circle cx="115" cy="110" r="50"></circle> 
    <path d="M115,110 L115,0 A50,50 1 0,1 190,35 z"></path> 
</svg> 

注入到我的HTML如果我將此代碼複製並粘貼到一個不同的.html文件並運行它,我得到的出現形狀(不完全的圓形)。這在我的實際網頁中不會發生。

我可以得到形狀出現,如果我直接在HTML文件中把上面的代碼(即,不使用Javascript函數來動態地計算並注入它)。

我使用Angular.js,如果有差別。

我不認爲有在我的JavaScript錯誤,因爲注入到HTML頁面的代碼在其他地方工作,但我可以張貼我的Javascript代碼,如果這將有助於。沒有任何樣式可以阻止SVG的出現。這幾乎就像我需要告訴瀏覽器重新加載/重新繪製/重新分析HTML,但我不確定。

感謝您的幫助。

編輯:

這是我的javascript代碼。

/* 
<svg> 
    <circle cx="115" cy="115" r="110"></circle> 
    <path d="M115,115 L115,5 A110,110 1 0,1 190,35 z"></path> 
</svg> 
*/ 
Sector.prototype.draw = function() { 
    // Create our svg element 
    var svg = document.createElement('svg'); 

    // Create and set up our circle element 
    var circ = document.createElement('circle'); 
    circ.setAttribute('cx', this.startX); 
    circ.setAttribute('cy', this.startY); 
    circ.setAttribute('r', this.radius); 

    //Create and set up our path element 
    var p = document.createElement('path'); 
    var dForPath = this.dString(this.startX, this.startY, this.radius, this.angle); 
    p.setAttribute('d', dForPath); 

    // Add our circle and path to the svg 
    svg.appendChild(circ); 
    svg.appendChild(p); 

    return svg; 
}; 

和我的使用

var sec = new Sector(115, 115, 110, 7); 
var c = sec.draw(); 

document.getElementById('circleTest').appendChild(c); 
// Weird issue. The following line makes the svg appear; 
// without it, the shape isn't drawn at all. 
// http://stackoverflow.com/questions/21347833/html-svg-not-drawing-works-in-other-pages 
document.getElementById('circleTest').innerHTML += ''; 
+0

@RobertLongson我編輯的問題,包括我的javascript。謝謝。 – matthewpalmer

回答

1

不能使用的createElement與SVG必須使用createElementNS代替即

var svg = document.createElement('svg'); 

應該

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 

而你需要的所有其他SVG元素你」做同樣的重新創建。

的innerHTML的解決方法,你已經找到了將修復府的命名空間,但最好是在第一時間正確地創建內容。

+0

謝謝!我是否還需要爲''path'和'circle'元素使用'createElementNS'?我需要爲這些使用什麼'namespaceURI'?另外,是否有更好/更標準的方法來將我的元素從Javascript插入到HTML中? – matthewpalmer

+0

與我上面提供的相同namespaceURI。這是標準的方式。 –

+0

太棒了!非常感謝你的幫助。 – matthewpalmer

0

我能得到的形狀,通過添加被注入我的SVG爲circleTest下面的代碼行

document.getElementById('circleTest').innerHTML += ''; 

出現。我不知道爲什麼這解決了這個問題。

相關問題