gpt4 book ai didi

javascript - D3 鼠标同时在两个图形上移动

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:07 26 4
gpt4 key购买 nike

如何同时捕获鼠标悬停在两个图形上的事件。我需要做如下图所示的事情:

enter image description here

任何人都可以指导我如何处理这个问题吗?。到目前为止,我能够让简单的鼠标悬停对单个图形起作用。

最佳答案

我是 function-plot 的作者它能够将事件分派(dispatch)到多个图形,例如,其中一个是 mouseover

var width = 300
var height = 180
var a = functionPlot({
target: '#a',
height: height,
width: width,
data: [{ fn: 'x^2' }]
})
var b = functionPlot({
target: '#b',
height: height,
width: width,
data: [{ fn: 'x' }]
})
a.addLink(b)
b.addLink(a)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/function-plot/1.16.5/function-plot.js"></script>

<span id="a" />
<span id="b" />

解决方案涉及让每个图形在触发特定事件时执行某些操作,例如 d3 调度事件的方式是

 // create a dispatcher with the events you will fire in the future
var dispatch = d3.dispatch('mycustomevent');
// add some callbacks (note the namespace)
dispatcher.on('mycustomevent.graph1, function (str) {
// when called str === 'hello world'
})
dispatcher.on('mycustomevent.graph2, function (str) {
// when called str === 'hello world'
})
// fire the event from the dispatcher
// the two callbacks attached are called in the same order
dispatch.mycustomevent('hello world')

在实践中,每当您将鼠标悬停在图表上而不是立即执行操作时,您会触发一个自定义事件并让每个图表在鼠标悬停时做任何它需要做的事情

 // create a dispatcher
var dispatch = d3.dispatch('mymouseover');

function graphWrapper(graph) {
return function (xCoord) {
// do something with `xCoord` in `graph`
}
}
dispatcher.on('mymouseover.graph1, graphWrapper(graph1))
dispatcher.on('mymouseover.graph2, graphWrapper(graph2))

// graph1 and graph2 need to fire the custom event
function dispatchMouseOver() {
var xCoord = x.invert(d3.mouse(this)[0])
dispatch.mymouseover(xCoord)
}
graph1.on('mousemove', dispatchMouseOver)
graph2.on('mousemove', dispatchMouseOver)

对于我修改的实现 an example made by d3's author由@In code veritas 引用,带有可重复使用的图表

a reusable graph with independent mouseover

如你所见,每个图都是相互独立的,在实现发布-订阅模式后,它看起来像这样

linked graphs

作为旁注,我基本上使用节点的事件模块在函数图中实现了这个功能,因为在 d3 中,您在同一命名空间下使用不同的名称添加了一个回调,例如mymouseover.1mymouseover.2 等等,但在节点的事件模块中,您只需执行 graph.on('event', callback) 多个次

关于该主题的有用文章/演示

关于javascript - D3 鼠标同时在两个图形上移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36992475/

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