gpt4 book ai didi

javascript - d3 - 向路径添加标记

转载 作者:行者123 更新时间:2023-11-28 07:30:44 24 4
gpt4 key购买 nike

我正在尝试在 Google map 叠加层上进行可视化,其中我用节点表示点,用边表示节点之间的链接。这些节点和边是使用 JavaScript 的 d3 库生成的。路径是根据 json 文件生成的。我现在想做的是在每条路径的末尾添加一个箭头标记,以指示路径的方向。为此我使用了 this example ,并首先指示 d3 在 defs 元素中添加包括其路径的标记,并且在生成路径期间,指示 d3 使用“marker-end”属性包含标记,其值通过其 id 引用标记元素使用 url 属性。下面显示了在每个路径中定义和引用标记的代码片段。

d3.json("./json/routes.json", function(route_data) {

var defs = layerPaths.append("defs")

/* here I generate the marker shape and assign it the "arrow" id */
defs.append("marker")
.attr({
"id": "arrow",
"viewBox": "0 -5 10 10",
"refX": 5,
"refY": 0,
"markerWidth": 4,
"markerHeight": 4,
"orient": "auto"
})
.append("path")
.attr("d", "M 0 -5 L 10 0 L 0 5")
.attr("class", "arrowHead");

/* here I start generating the paths */
var path = layerPaths.selectAll("path")
.data(route_data)
.each(setPathProperties)
.enter()
.append("path")
.each(setPathProperties); // path properties are set by the setPathProperties function

function setPathProperties(d) {

/* I removed the complex functions that calculate path position as these are irrelevant for the question*/

/* select the current path element and add attributes*/
d3.select(this)
.attr("class", "path")
.attr("d", svgPen)
.attr("stroke", "blue")
.attr("stroke-width", 10)

/* add the marker to the path by refering with a url statment to the marker element with the arrow id */
.attr("marker-end", "url(#arrow)");
}

})

加载 map 后,节点和路径会加载,但箭头不会出现。然而,marker-end 属性(包括其引用)位于每个路径元素中,而标记元素(包括其定义路径)位于 HTML 中。我认为“marker-end”属性的值“url(#arrow)”不起作用,尽管我不知道为什么。

有谁知道这里出了什么问题,为什么标记没有显示在 map 上,以及如何解决这个问题?

最佳答案

您可以首先在 svg 元素中创建 defs,然后在其中创建标记,如下所示

  svg.append("svg:defs").append("svg:marker")
.attr("id", "triangle")
.attr("refX", 13)
.attr("refY", 5)
.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", "#555");

并通过marker-end和marker-start属性将此标记添加到您的路径中,如下所示

 var link = svg.append('g')
.attr('class', 'links')
.selectAll('path')
.data(graph.links)
.enter().append('path')
.attr("marker-end", "url(#triangle)")

关于javascript - d3 - 向路径添加标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com