在 D3.js 中缩放或平移时限制域 [英] Limiting domain when zooming or panning in D3.js

查看:15
本文介绍了在 D3.js 中缩放或平移时限制域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个简单的 D3.js 折线图,可以缩放和平移.它基于 Stephen Bannasch 的优秀示例此处.

I have implemented a simple D3.js line chart that can be zoomed and panned. It is based on Stephen Bannasch's excellent example here.

我的数据域在 x 维度上是 [0, n].

The domain of my data is [0, n] in the x dimension.

如何使用内置缩放行为(即使用鼠标滚轮事件)限制对该域的缩放和平移?

How can I limit zooming and panning to this domain using the built-in zoom behavior (i.e. using mousewheel events)?

我想防止用户在下端平移超过 0 或在上端平移超过 n,例如,他们应该永远无法看到 x 轴上的负值,并希望将缩放限制在同一窗口.

I want to prevent users from panning past 0 on the lower end or n on the upper end, for example they should never be able to see negative values on the x-axis, and want to limit zooming to the same window.

我发现的基于 Jason Davies 的示例使用 extent( [...],[...],[...] ) 似乎不再适用于 2.9.1 版.遗憾的是,缩放行为目前是其他出色的 API 文档中未记录的少数功能之一.

The examples that I found based on Jason Davies work using extent( [...],[...],[...] ) seem to no longer work in version 2.9.1. Unfortunately, the zoom behavior is currently one of the few features not documented in the otherwise outstanding API documentation.

欢迎任何指点.

附注.我在 D3.js 邮件列表上发布了同样的问题,但没有得到回复:https://groups.google.com/d/topic/d3-js/w6LrHLF2CYc/discussion.为交叉发布道歉.

PS. I have posted the same question on the D3.js mailing list but did not get a response: https://groups.google.com/d/topic/d3-js/w6LrHLF2CYc/discussion. Apologies for the cross-posting.

推荐答案

您只需要在重绘时限制域.以下代码将防止图形缩小超过其初始域(如 http://bl.ocks.org/1182434).

You just need to limit the domain on redraw. The following code will prevent the graph from being zoomed out past it's initial domains (as used in http://bl.ocks.org/1182434).

SimpleGraph.prototype.redraw = function() {
  var self = this;
  return function() {

    self.x.domain([Math.max(self.x.domain()[0], self.options.xmin), Math.min(self.x.domain()[1], self.options.xmax)]);

    self.y.domain([Math.max(self.y.domain()[0], self.options.ymin), Math.min(self.y.domain()[1], self.options.ymax)]);

    ....

这篇关于在 D3.js 中缩放或平移时限制域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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