ChartJs: How to pan programmatically by time values (instead of pixels)

1.5k Views Asked by At

I'm using chartJs 3.6.1; and chartjs-plugin-zoom 1.2.1 (but I think it's not really matter :)) I have 2 timeseries line chart, and when I panning one chart via drag&drop, I want to move/pan the other graph as well!

For that I enabled zoom/pan for graphA - graphA.zoom.pan.enabled=true, and it has the onPanComplete function which when I want to run the panning for graphB. Have no problem with zoom - it has graphA.getZoomLevel() function; so that I can use graphB.zoom(graphA.getZoomLevel()). * But what is the case with panning? Edit: *No, it's not good. It's use different scale, some kind of exponencial... like... 1.0 mean 1.0, but 1.5x mean ~1.7x zoom, 1.98x mean 50x zoom, and 2x mean infinite (which is 80.000x zoom)

So far, I can get the visible area: chart.scales.xAxes.min (...and max) - but it gives back time values that is currently visible! The pan() function waiting for pixels: graphB.pan(100, undefined, undefined), and also it just an offset from the current position, not an absolute position set. Can I say somehow "move the graph left by 1 minute"? I saw some kind of "scale" setting, but I don't understand how it works... Or the best could be to say: "move the graph to start with 2022.03.01 12:00:00"! Or.. for a workaround, I can calculate the pixels, but for that I need to know the width of the chart data, but it's a big "canvas" and can't get it.

3

There are 3 best solutions below

1
On BEST ANSWER

I found the solution after all! Yeah :))

You can zoom by adding the min and max value! No need for pixels at all! Use zoomScale method! zoomScale(graphB, 'xAxes', {min: graphA.scales.xAxes.min, max: graphA.scales.xAxes.max}, 'none'); (The scale is 'xAxes' for me, I don't know why the examples on offical pages says a simple 'x')

1
On

You can use the getPixelForValue method on the x axes. You do this for 2 time points from which you know how far they are appart from each other. Then you can calculate how many pixels you will need to shift the chart for any time frame you want.

Edit:
If you just want the width of the chartArea you can do it like so:

const chart = new Chart(ctx, config);
const chartAreaWidth = chart.chartArea.width;
0
On

Solution from @cncDAni3's answer is worked for me.

In React with react-chart-js2, using a ref:

ref.zoomScale("xAxes", { min: minX, max: maxX }, <mode>)