我目前正在构建一个平台,用于映射一些需要在 map 中的节点之间绘制线条的数据。现在,我已经创建了这些行
(Picture 1 (fill: none
))。此外,我打算在我已经完成的行中添加一个点击监听器。不幸的是,该路径似乎有一个填充区域,该区域也监听事件并与其他路径重叠,这使得无法单击其下方的路径( Picture 2 default fill attr )。我尝试设置 fill: none
(如第一张图片所示),但似乎只是删除了颜色,而不是填充区域。
这是我添加行的代码:
function createPath(company) {
//Create Paths Line
var linePathGenerator = d3.line()
.x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
})
.curve(d3.curveMonotoneX);
// Add Path to the Line Layer
var svgPath = layerArc.append("path")
.attr("stroke", companyConfig[company].color)
.attr("stroke-width", "1.5px")
.attr("fill", "none")
.style("opacity", 0.6);
var d = linePathGenerator(adjency[company])
var line = svgPath.attr("d", d)
// Click Listener
line
.on('click', function() {
if (!d3.select(this).classed("active")) {
layerArc.selectAll('path')
.attr("stroke-width", "1.5px")
.style("opacity", 0.6);
d3.select(this)
.attr("stroke-width", 3)
.style("opacity", 1)
.attr("class", "active")
d3.selectAll(".nodes svg circle")
.style("stroke", 'none')
var circles = d3.selectAll(".nodes svg")
circles = circles.filter(function(d) {
return d.value.company == company
})
circles.select('circle').style("stroke", 'white')
.style("stroke-width", 2)
} else {
layerArc.selectAll('path')
.attr("stroke-width", "1.5px")
.style("opacity", 0.6)
.attr("class", "deactive")
d3.selectAll(".nodes svg circle")
.style("stroke", 'none')
}
})
var totalLength = svgPath.node().getTotalLength();
svgPath
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(4000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
}
有人知道如何完全删除填充吗?或者关于如何以相同的方式绘制线条但没有路径的任何其他建议?
最佳答案
在我看来,您只是希望当用户单击路径的笔画时触发监听器,而不是单击其填充(会产生困惑,因为您使用术语“line”,这意味着 SVG 中的另一件事)。
如果这是正确的,解决方案很简单,您只需设置 pointer-events通往 visibleStroke
的路径或stroke
:
.attr("pointer-events", "visibleStroke");
这是一个演示,您可以单击填充或路径外部,但什么也不会发生,单击其描边,监听器就会触发:
var svg = d3.select("svg");
var path = svg.append("path")
.attr("d", "M50,20 L250,20 L250,130 L50,130 Z")
.style("fill", "teal")
.style("stroke", "black")
.style("stroke-width", 4)
.attr("pointer-events", "visibleStroke")
.on("click", function() {
console.log("clicked")
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
此外,值得一提的是,您的代码中存在问题:如果您将填充设置为 none
,默认pointer-events
不应该不触发。这是一个演示:
var svg = d3.select("svg");
var path = svg.append("path")
.attr("d", "M50,20 L250,20 L250,130 L50,130 Z")
.style("fill", "none")
.style("stroke", "black")
.style("stroke-width", 4)
.on("click", function() {
console.log("clicked")
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
关于javascript - 完全删除 D3 中的路径填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675853/