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

标签 javascript d3.js nvd3.js

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

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/

相关文章:

javascript - float 在页面上并充当 anchor 的按钮

javascript - D3.js强制布局: How to stop initial movement in force layout graph?

javascript - Angular-Nvd3 日期和数字与数据不匹配

IE WebBrowser 控件不支持 Javascript 'map'?

javascript - 获取所有刻度值 (NVD3)

javascript - 如何使用 json 数据在 d3.js 中创建垂直分组的条形图?

javascript - Bootstrap 2 或 3 Modal 中的 Kendo Grid - IE 过滤器不起作用

javascript - ES6 Node.js 导入然后重写文件?

javascript - 过滤两个对象的值

javascript - 动态投影单个县