简体   繁体   中英

Update drag/scroll origin after an update of the data with transition in D3

I work on a chart with dragging, zooming and updates. This mostly works, however, after adding new data, the dragging position does not update.

Steps to reproduce:

  • see the demo
  • wait some seconds so that some data is added to the graph
  • then try dragging the graph to the left or right
  • the graph will be pushed back to the beginning and from that point dragging works the way it should

So I guess, when adding new data, I somehow have to update the drag origin. But how? So far I was not able to find any example of that. I also looked at the code of the dragging functionality of D3 , but it's still not clear to me. Same thing happens for the zooming, I guess it is the same problem there.

Code and demo can be seen here: http://jsbin.com/irixag/1/edit

Edit: If it is not clear what I mean, please tell me so that I can rephrase the question.

Okay, I've been sifting through your code and the d3.js source and I've noticed a couple of things.

First, the gist of my solution is to add

function update() {
    ...
    if (shiftRight) {
        zoom.x(x); // You're missing this line
        ...
    }
    ...
}

Here's why:

You are initializing the horizontal drag and drop by using the .x(x) call on the d3.behavior.zoom() object. This looks fine, except this drag & drop handler is not designed for a varying origin.

Basically, when you call d3.behavior.zoom().x(x) you are declaring that right now the value of x is the origin. Now, d3.js stores this value, so even though you are shifting the window right in an animation loop, drag & drops will still honor that original origin.

In the d3.behavior.zoom source there are three variables of interest, x0 , x1 , and translate . x1 is a reference to the current value of the x variable you passed in. x0 is the copied value of x when you initially passed it in. translate is the aggregate translation of all your drag+drops combined.

Now, conveniently, calling zoom.x(x) resets all three of these variables, which means the translation will only be aggregated against the current origin, and the origin will reflect your shifting window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM