2014-10-20 74 views
0

我一直在試圖實現這個代碼來創建一種圖形,用戶在畫布上單擊以創建一個節點,然後可以再次單擊任意兩個節點以繪製邊緣在他們之間也能夠輸入與該邊緣相關的重量。我不明白爲什麼路徑功能沒有響應。 可能在語句中可能存在語法錯誤svg的路徑功能沒有響應

pathE1.setAttribute(「d」,「M coord1,coord2 L coord3,coord4」);

但我無法弄清楚什麼是正確的way.here是我的代碼:

<!DOCTYPE html> 
<html> 
<svg id="canvas" height="1260" width="1260"> 
</svg> 
<script src="jquery-1.11.1.min.js"> 

</script> 
<script> 
    var check; 
var circles = []; 

$(document).ready(function() { 
    $("#canvas").bind("mousedown", function(e) { 
     var coords = getCoords(e); 

     var result = inCircle(coords.x, coords.y); 

     if (typeof result === "number") { 

      check = result + 1; 

     } else { 
      draw(coords.x, coords.y); 
     } 

    }); 
    $("#canvas").bind("mouseup", function(e) { 
     if (!check) { 
      console.log('hey'); 
      return; 
     } 
     var coords = getCoords(e); 
     var result = inCircle(coords.x, coords.y); 

     console.log(result); 
     if (typeof result === "number") { 
      //alert('node up'); 
      drawConnection(check - 1, result); 
     } 
     check = 0; 

    }); 




    function getCoords(e) { 
     var x = e.clientX; 
     var y = e.clientY; 
     //alert('x:' +x+ ' y:' +y); 
     return { 
      x: x, 
      y: y 
     }; 
    } 

    function inCircle(x, y) { 

     for (var i = 0; i < circles.length; i++) { 
      if (distance(x, y, circles[i].x, circles[i].y) <= 20) { 
       return i; 
      } 
     } 
    } 

    function draw(x, y) { 
     circles.push({ 
      x: x, 
      y: y 
     }); 

     var circle1 = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
     circle1.setAttribute("cx", x); 
     circle1.setAttribute("cy", y); 
     circle1.setAttribute("r", 20); 
     circle1.style.fill = 'blue'; 
     circle1.style.stroke = 'blue'; 
     circle1.style.strokeWidth = '5'; 
     $('#canvas').append(circle1); 
    } 

}); 


function distance(x, y, cx, cy) { 
    return Math.sqrt((cx - x) * (cx - x) + (y - cy) * (y - cy)); 
} 

function drawConnection(circ1, circ2) { 
    var dist = prompt("enter weight"); 
    var coord1 = circles[circ1].x, 
     coord2 = circles[circ1].y, 
     coord3 = circles[circ2].x, 
     coord4 = circles[circ2].y; 
    var pathE1 = document.createElementNS("http://www.w3.org/2000/svg", "path"); 
    pathE1.setAttribute("d", "M coord1 , coord2 L coord3 , coord4"); 

    pathE1.style.stroke = 'red'; 
    pathE1.style.strokeWidth = '5'; 

    $('#canvas').append(pathE1); 
} 
</script> 

回答

0
pathE1.setAttribute("d", "M coord1 , coord2 L coord3 , coord4"); 

只是要創建一個文本座標1爲X的路徑而不是協調1的。你想要的是

pathE1.setAttribute("d", "M " + coord1 + ", " + coord2 + " L " + coord3 + ", " + coord4);