D3图形:我试图添加标签到D3图形中创建的箭头,但它没有被添加



我对d3.js相当陌生,我在d3图形中创建了两个箭头,我试图在箭头的中心添加文本,但我无法看到添加到箭头的标签。

我的codependency链接在下面:

https://codepen.io/Navin_Kris/pen/mdXwVoY

代码如下

const data = [ { x1: 50, y1: 50, x2: 200, y2: 50, label: 'Arrow 1', rotation: '0', arrowcolor: '#62b6ae'},
{ x1: 50, y1: 70, x2: 200, y2: 70, label: 'Arrow 2', rotation: '180', arrowcolor: '#e71c1d'}]
var svg = d3.select('svg');
for(let d of data){
var line = svg.append("line")
.attr("d", "line_path")
.attr("x1",d.x1)  
.attr("y1",d.y1)  
.attr("x2",d.x2)  
.attr("y2",d.y2)  
.attr("stroke", d.arrowcolor)  
.attr("stroke-width",2)  
.attr("marker-end", markercolor(d.arrowcolor))
.attr("rotate", d.rotation); 

var value = d3.select('line');
value.append("text")
.attr("dy", 30)
.style("text-anchor", "middle")
.text(d.label);
}
function markercolor(color) {
svg.append("svg:defs").append("svg:marker")
.attr("id", color.toString().replace("#", ""))
.attr("refX", 6)
.attr("refY", 6)
.attr("markerWidth", 30)
.attr("markerHeight", 30)
.attr("markerUnits","userSpaceOnUse")
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 12 6 0 12 3 6")
.style("fill", color);
return "url(" + color + ")";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="300" height="200">
</svg>

你能帮我一下吗?

修复了它,为任何有相同问题的人发布修复:

for(let d of data){
var line = svg.append("line")
.attr("d", "line_path")
.attr("x1",d.x1)  
.attr("y1",d.y1)  
.attr("x2",d.x2)  
.attr("y2",d.y2)  
.attr("stroke", d.arrowcolor)  
.attr("stroke-width",2)  
.attr("marker-end", markercolor(d.arrowcolor))
.attr("rotate", d.rotation); 

svg.append("text")
.attr("dx", (d.x1 + d.x2)/2)
.attr("dy", d.y1)
.style("text-anchor", "middle")
.text(d.label);
}

最新更新