2014-05-16 65 views
0

我試圖讓Snap.svg在我的Rails項目中工作。無法獲取Snap.svg在Rails中選擇正確的svg元素

我有一個頁面foo.html.slim包含以下代碼:

#svg-container 
    svg#apple height="1000" width="400" 

而在static_pages.js.coffee,我有

svgElement = document.getElementById("apple") 
paper = Snap(svgElement) 
circ = paper.circle(100, 100, 50) 
circ.attr 
    fill: "#ff0000" 
    stroke: "#0000ff" 
    strokeWidth: 10 
circ.drag() 

這不隨地呈現SVG的頁面(元素ISN」上t在html源碼中);然而,如果我在一個特定的地方添加一條線,就像這樣

svgElement = document.getElementById("apple") 
document.write("foo") # this is the new line 
paper = Snap(svgElement) 
circ = paper.circle(100, 100, 50) 
circ.attr 
    fill: "#ff0000" 
    stroke: "#0000ff" 
    strokeWidth: 10 
circ.drag() 

繪製紅色和藍色圓圈。問題在於它位於html正文的最頂端,而不是它應該選擇的svg元素。同樣值得注意的是,如果document.write("foo")行放置在咖啡腳本文件的不同位置,則該圓圈不會被繪製。

paper = Snap("#apple")也不能代替原來的代碼。

在現有的svg元素中繪製svg圓的正確方法是什麼?

+0

您是否需要一個'$ - >'包裝來確保'#apple'在您尋找時出現? –

+0

是的,當javascript嘗試訪問它時'svgElement'爲null。我需要結束什麼功能?爲了檢查,我在頁面上放置了一個按鈕,用於調用整個javascript代碼。這是行得通的,但只有當我將函數定義直接放入html中,而不是當JavaScript位於Rails資產樹上時。 – Sandy

回答

0

聽起來像你試圖訪問#apple之前它在那裏。最簡單的解決方法是換一個需要在文檔準備處理#apple代碼,在CoffeeScript中,將是這樣的:

$ -> 
    svgElement = document.getElementById("apple") 
    paper = Snap(svgElement) 
    circ = paper.circle(100, 100, 50) 
    circ.attr 
    fill: "#ff0000" 
    stroke: "#0000ff" 
    strokeWidth: 10 
    circ.drag() 

這是一樣在JavaScript $(function() { ... })