2015-08-29 67 views
1

我想在每行的末尾使用.append("svg:marker")生成簡單的箭頭。我顯然做錯了事 - 非常感謝。在d3js中生成箭頭

A link to bl.ocks example .

var svg = d3.select("body") // select the 'body' element 
 
     .append("svg")   // append an SVG element to the body 
 
     .attr("width", 600)  
 
     .attr("height", 600); 
 

 

 
d3.csv("data/myarrows.csv", dottype1, function(error, lines) { 
 
    
 
svg.append("g") 
 
     .selectAll("line") 
 
     .data(lines) 
 
     .enter() 
 
     .append("line") 
 
     .attr("x1", function(d) { return d.x1; }) 
 
     .attr("y1", function(d) { return d.y1; }) 
 
     .attr("x2", function(d) { return d.x2; }) 
 
     .attr("y2", function(d) { return d.y2; }) 
 
     .style("stroke", "brown")   // colour the line 
 
     .style("stroke-width", 4)   // adjust line width 
 
     .style("stroke-linecap", "square") // stroke-linecap type 
 
     
 

 
svg.append("g") 
 
     .selectAll("marker") 
 
     .data(lines) 
 
     .enter() 
 
     .append("svg:marker") 
 
     .attr('viewBox', '0 -5 10 10') 
 
     .attr('refX', 6) 
 
     .attr('markerWidth', 10) 
 
     .attr('markerHeight', 10) 
 
     .attr('orient', 'auto') 
 
     .append('svg:line') 
 
     .attr('d', 'M0,-5L10,0L0,5') 
 
       ; 
 
}); 
 

 

 

 

 
function dottype1(d) { 
 
    d.x1 = +d.x1x1; 
 
    d.y1 = +d.y1y1; 
 
    d.x2 = +d.x2x2; 
 
    d.y2 = +d.y2y2; 
 
    return d; 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>Arrows</title> 
 
    <meta charset="utf-8" /> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 

 
</head> 
 

 

 
<body>  
 
    
 
<script type="text/javascript"> 
 

 
    </script> 
 

 
</body> 
 
</html>

回答

2

有不少東西錯了:

  1. 你只需要一個標記,然後您可以通過ID號和名稱。見docs
  2. 標記應該在defs而不是g,但它並不重要。
  3. 您使用line而不是path,但只有path具有d屬性。

在代碼中,這意味着:

svg.append("g") 
     .selectAll("line") 
     .data(lines) 
     .enter() 
     .append("line") 
     .attr("x1", function(d) { return d.x1; }) 
     .attr("y1", function(d) { return d.y1; }) 
     .attr("x2", function(d) { return d.x2; }) 
     .attr("y2", function(d) { return d.y2; }) 
     .attr("marker-end", "url(#triangle)") // add the marker 
     .style("stroke", "brown")   // colour the line 
     .style("stroke-width", 4)   // adjust line width 
     .style("stroke-linecap", "square") // stroke-linecap type 
       ; 

svg.append("svg:defs") 
     .append("svg:marker") 
     .attr("id", "triangle") 
     .attr('viewBox', '0 -5 10 10') 
     .attr('refX', 6) 
     .attr('markerWidth', 10) 
     .attr('markerHeight', 10) 
     .attr('orient', 'auto') 
     .append('svg:path') 
     .attr('d', 'M0,-5L10,0L0,5') 
       ; 
}); 

我沒但是測試此代碼,我只試過這種手工的devtools。