第一个缩放事件删除了中心变换 [英] First zoom event removes center-transform

查看:78
本文介绍了第一个缩放事件删除了中心变换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵像这样的辐射整齐的树: https://bl.ocks.org/ mbostock / 4063550

I have a 'Radial Tidy Tree' like this: https://bl.ocks.org/mbostock/4063550

我正在尝试添加缩放和平移,但是我无法同时使缩放和平移正常工作。

I am trying to add zooming and panning, but I am not able to get both zooming and panning to work properly.

我的代码如下所示:

var width = 1000,
    height = 800;

var zoom = d3.zoom()
    .scaleExtent([1 / 2, 4])
    .on("zoom", zoomed);

var svg = d3.select('.svg-container').append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr('preserveAspectRatio', 'xMinYMin')
    .call(zoom);

var g = svg.append("g").attr(
    "transform",
    "translate(" + width / 2 + "," + height / 2 + ") scale(1)"
);

function zoomed() {
    g.attr(
      "transform",
      d3.event.transform
    );
}

当我第一次拖动或滚动时, em> g 元素跳到左上方。第一个 d3.event.transform 输出以下内容:

When I drag or scroll for the very first time, the g element jumps to the top left. The very first d3.event.transform outputs this:

{k: 1, x: 0, y: 0}

如果在此之后进行缩放或平移,效果很好。

If I zoom or pan after that, it works fine.

当我尝试以下操作时:

function zoomed() {
    var x = (width / 2) + d3.event.transform.x;
    var y = (height / 2) + d3.event.transform.y;

    g.attr(
      "transform",
      "translate(" + x + "," + y + ") scale(" + d3.event.transform.k + ")"
    );
}

g 元素不会跳到顶部向左和平移效果很好,但是缩放不会根据鼠标位置进行缩放(仅当鼠标位于左上角时才能正确工作)。

the g element does not jump to the top left and panning works fine, but the zooming does not zoom based on the mouse position (only works correctly when the mouse is in the top left corner).

推荐答案

由于 d3 存储元素,因此将元素放大到本身,它需要知道将作为缩放一部分的所有变换。在您的情况下,您已通过 .attr 调用(而不是缩放)设置了初始位置,所以 d3 不知道。要通过缩放设置它,请执行以下操作:

Since d3 stores an elements zoom on the element itself, it needs to know about all transforms that'll be part of the zoom. In your case, you've set the initial position via a .attr call (and not the zoom), so d3 doesn't know about it. To set it via the zoom instead do:

var width = 1000,
    height = 800;

var zoom = d3.zoom()
    .scaleExtent([1 / 2, 4])
    .on("zoom", zoomed);

var svg = d3.select('.svg-container').append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr('preserveAspectRatio', 'xMinYMin')
    .call(zoom);

var g = svg.append("g");

// set initial position via zoom
svg.call(zoom.transform, d3.zoomIdentity.translate(width/2, height/2));

function zoomed() {
    g.attr(
      "transform",
      d3.event.transform
    );
}

工作示例

这篇关于第一个缩放事件删除了中心变换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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