【发布时间】:2022-01-06 19:39:37
【问题描述】:
我正在尝试在使用 d3 呈现的 svg 路径上创建方向箭头。我使用路径字符串和svg-path-properties npm 包获取起点。然后,我将这些点推送到一个数组中,并在另一个函数中,使用 d3 逻辑将这些点映射到原始 svg 路径上,以在每个点处创建三角形。
public mapArrowPoints(): void {
this.arrowPoints.forEach((point: ArrowPointObject) => {
const path = d3.path();
path.moveTo(parseInt(point.x, 10), parseInt(point.y, 10));
path.lineTo(parseInt(point.x, 10) + 8, parseInt(point.y, 10) + 2);
path.lineTo(parseInt(point.x, 10) + 0, parseInt(point.y, 10) + 8);
path.closePath();
const svg = d3.select('svg#topLevel');
const defs = svg.insert('defs', '#curve');
const marker = defs.append('marker');
marker
.attr('id', 'triangle')
.attr('viewBox', '0 -5 10 10')
.attr('markerWidth', 4)
.attr('markerHeight', 4)
.attr('orient', 'auto')
.append('path')
.attr('d', path.toString())
.attr('fill', 'red')
.attr('stroke', 'black')
.attr('stroke-width', '3px');
svg
.select('#curve')
.attr('marker-start', 'url(#triangle)')
.attr('marker-mid', 'url(#triangle)')
.attr('marker-end', 'url(#triangle)');
});
}
现在,当我检查浏览器时,我可以看到我的主路径,但看不到三角形。我可以检查 DOM,并查看应该附加到的 svg、defs、marker 和 path。我还可以选择标记路径本身,并查看它应该在哪里渲染(蓝色框显示三角形应该在哪里)。我不太明白为什么三角形没有显示出来。任何帮助都感激不尽。我创建了一个stackblitz example 用于试验解决方案。
【问题讨论】:
-
你有 108 个箭头点,所以你创建了 108 个 defs 元素,每个元素都有一个 id="triangle" 的元素。所有 id 值都必须是唯一的,而你的不是。
-
这是有道理的。我是 svg 的新手,所以还有很多东西要学。谢谢@RobertLongson!