D3:重新映射鼠标滚轮而不是缩放手势 [英] D3: remap mousewheel to be panning gesture instead of zoom gesture

查看:638
本文介绍了D3:重新映射鼠标滚轮而不是缩放手势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,在D3中创建新的缩放行为时,它会将鼠标滚轮映射到控制缩放级别。如果图表大于图表区域,也可以单击并拖动以平移图表。我想重新映射鼠标滚轮手势,而不是在垂直轴上平移(鼠标滚轮向上平移,鼠标滚轮向下平移)。任何人都有任何线索如何实现这一目标?

By default, when you create a new zoom behavior in D3, it maps the mousewheel to control zoom level. You can also click and drag to pan the chart if it's larger than the chart area. I'd like to remap the mousewheel gesture to instead pan on the vertical axis (mousewheel up pans up, mousewheel down pans down). Anyone have any clue how to accomplish this?

推荐答案

好的,我们走了:
基于Lars'评论,我们可以为mousewheel事件指定事件处理程序。如答案所示,我们首先映射 wheel.zoom 自定义处理程序的事件 pan

Ok, here we go: Based on Lars' comment, we can specify event handler for mousewheel event. As shown in the answer, we start by mapping wheel.zoom event to a custom handler pan

selection.call(zoomer)
      .on("wheel.zoom",pan) // handler function for mousewheel zoom

其次,我们需要定义平移手势,它基本上是 x translate >和/或 y 方向。

Second, we need to define the pan gesture, which is basically a translate in x and/or y direction.

function pan() {
  svg.attr("transform", "translate(" + [dx,dy] + ")");
}

我们还需要量化两个方向的运动,并将其与鼠标轮相关联运动。通过检查 MouseWheel 事件的详细信息,我们发现两个有用的属性 deltaX deltaY ,表示鼠标滚轮的移动量每个方向。

We also need to quantify the movement in both directions, and relate it to mousewheel movement. By inspecting the details of MouseWheel event, we find two useful attributes deltaX and deltaY, indicating how much the mousewheel moved in each direction.

最终的 pan 函数如下:

function pan() {
    current_translate = d3.transform(svg.attr("transform")).translate;
    dx = d3.event.wheelDeltaX + current_translate[0];
    dy = d3.event.wheelDeltaY + current_translate[1];

  svg.attr("transform", "translate(" + [dx,dy] + ")");
  d3.event.stopPropagation();
}

这是工作小提琴 bl.ock 还修改了Mike的几何缩放示例

Here is a working fiddle and bl.ock also modifying Mike's geometric zoom example.

似乎鼠标轮事件在浏览器之间有所不同。对于Safari和Firefox支持,您需要添加以下内容:

It seems that mousewheel events differs between browsers. For Safari and Firefox support, you need to add the following:

selection.call(zoomer)
  .on("wheel.zoom",pan) 
  .on("mousewheel.zoom", pan)
  .on("DOMMouseScroll.zoom", pan)

此外,Firefox中反转 wheelDelta 的解释。 wheelDelta 可以通过这个修复功能

Also, the interpretation of wheelDelta is reversed in Firefox. wheelDelta can be fixed by this function

function crossWheelDelta()
  // cross-browser wheel delta
  var e = window.event || e; // old IE support
  return Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
}

这篇关于D3:重新映射鼠标滚轮而不是缩放手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆