2013-01-06 109 views
0

我有一個文本框,必須輸入座標的位置。然後點擊Set,將文本(座標)分配給變量c。並點擊繪製繪製一條路徑到定義的座標。RaphaelJS/Javascript更新路徑而不是創建新路徑

我想要做的是每次點擊繪製更新現有的路徑。但是,當我點擊Draw時,它所做的就是不斷創建新路徑。我哪裏錯了?

這裏是FIDDLE

<html> 
<head> 

<script src="raphael.js"></script> 
<script> 
var c, previous1, linepath; 
var l = 5; 
var x = 1; 

window.onload = function(){ 


    set = function(){ 
     c = document.getElementById("b1").value;//get the co-ords 
     circ();//draw circle at the select co-ord 
    } 

    var paper = Raphael(0,80,600,600); 


    draw = function(){ 
     if (x==1){ 
      previous1 = "M100,100 L"; 
      x++; 
     }else{ 
      previous1 = window.linepath + " "; 
     } 

     var new1 = previous1 + window.c; 
     linepath = new1; 
     var line = paper.path(linepath); 

     var path = paper.text(10,l,linepath); 
     path.attr({"text-anchor":"start","font-size":"12"}); 
     l = l+10;  
    }; 

    function circ(){ 
     var posX = c.substring(0,3); 
     var posY = c.substring(4,7); 
     var circl = paper.circle(posX,posY,5).attr({fill:'red',stroke:'none'}); 
    }; 


} 
</script> 


</head> 
<body> 
    Enter co-ords > Click Set > Click Draw 
    <br> 
    <input type="text" id="b1" value="100,400"> 
    <button type="button" onclick="set()">Set</button> 

    <button type="button" onclick="draw()">Draw</button> 

</body> 
</html> 

回答

6

簡單:你正在做一個新的Raphael.path()每次用戶點擊對象的「畫」,當你需要更新現有的(如果「繪製「已被點擊至少一次)。

//line needs to be declared outside the function, without an initial value 
if (typeof line === "undefined") { 
    line = paper.path(linepath);  
} else { 
    line.attr("path", linepath); 
} 

雖然我們在這裏,你不想承擔用戶爲座標進入三位數的值,如果你沒有建立該條件的限制。相反,從子輸入得到的x/y的值,這樣做:

var posX = parseInt(c.split(",")[0], 10); 
var posY = parseInt(c.split(",")[1], 10); 

updated fiddle

+0

感謝隊友,感謝您的諮詢。 –