gpt4 book ai didi

javascript - d3.brush清空后如何调用函数?

转载 作者:行者123 更新时间:2023-11-28 11:04:02 27 4
gpt4 key购买 nike

为了详细说明这一点,假设我们有一个典型的 d3 画笔用例,例如 example here by Mike Bostock 。当我单击画笔外的任何地方时,画笔会被清除。所以我希望在该事件被触发时执行一个函数。相关代码与 Mike 的示例非常相似。

最佳答案

在您提到的示例中,画笔被清除为由 “end” 监听器触发的默认行为。

惯用的 D3 解决方案是设置一个 "end" 监听器来检查 d3.event.selection 是否为 null:

brush.on("end", function() {
if(!d3.event.selection){
//your function here;
}
});

这里是使用Bostock的代码的demo,点击画笔外面,查看控制台消息:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis--grid .domain {
fill: #ddd;
stroke: none;
}

.axis--x .domain,
.axis--grid .tick line {
stroke: #fff;
}

.axis--grid .tick--minor line {
stroke-opacity: .5;
}

</style>

<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
var margin = {
top: 50,
right: 40,
bottom: 200,
left: 40
},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;

var x = d3.scaleTime()
.domain([new Date(2013, 7, 1), new Date(2013, 7, 15) - 1])
.rangeRound([0, width]);

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
.attr("class", "axis axis--grid")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.ticks(d3.timeHour, 12)
.tickSize(-height)
.tickFormat(function() {
return null;
}))
.selectAll(".tick")
.classed("tick--minor", function(d) {
return d.getHours();
});

svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.ticks(d3.timeDay)
.tickPadding(0))
.attr("text-anchor", null)
.selectAll("text")
.attr("x", 6);

svg.append("g")
.attr("class", "brush")
.call(d3.brushX()
.extent([
[0, 0],
[width, height]
])
.on("brush", brushed)
.on("end", function() {
if (!d3.event.selection) console.log("you clicked ouside the brush")
}));

function brushed() {
if (d3.event.sourceEvent.type === "brush") return;
var d0 = d3.event.selection.map(x.invert),
d1 = d0.map(d3.timeDay.round);

// If empty when rounded, use floor instead.
if (d1[0] >= d1[1]) {
d1[0] = d3.timeDay.floor(d0[0]);
d1[1] = d3.timeDay.offset(d1[0]);
}

d3.select(this).call(d3.event.target.move, d1.map(x));
}

</script>

关于javascript - d3.brush清空后如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52757788/

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