【问题标题】:Chart.js How to synchronize pan and zoom in multiple chatsChart.js 如何同步平移和缩放多个聊天
【发布时间】:2019-11-01 02:37:31
【问题描述】:

我想在多个图表上同步平移和缩放。 我一直在使用 Chart.js 和 chartjs-plugin-zoom。

charjs-plugin-zoom 使用 onZoom 回调函数调用事件。所以,X轴两端的值就是用回调函数这样获取的。

onZoom: function () {
    var minVal = myChartA.getDatasetMeta(0).dataset._scale.chart.scales['x-axis-0']._table[0].time;
    var maxVal = myChartA.getDatasetMeta(0).dataset._scale.chart.scales['x-axis-0']._table[1].time;

    leftEnd = minVal;
    rightEnd = maxVal;

    updateChart();
}

然后使用 updateChart 函数更新图表。

我以为其他图表应该用updateChart函数得到的X轴两端的值来更新。 使用 Chart.helpers.each 调用 update() 更新所有图表。

function updateChart() {
    Chart.helpers.each(Chart.instances, function (instance) {
        instance.oprions = {
            scales: [{
                xAxes: {
                    time: {
                        min: leftEnd,
                        max: rightEnd
                    }
                }
            }]
        };
        instance.update();
    });
}

但是,没有得到预期的结果。 Zoom-PAN 只反映被操作的图表。

我认为 onZoom 回调函数获取 X 轴的两个边缘,并每帧更新图表。 图表只能使用选项进行更新,因此 Chart.helpers.each 可用于一次更新所有图表。如果要更新的X轴两端都是全局变量,那么所有的图都可以引用。

这个方法不正确吗? 选项更新方法错了吗?更新时机不对吗?


更新

我通过参考https://www.chartjs.org/docs/latest/developers/updates.html了解了如何更新图表。

实际上,多个图表的 X 轴刻度范围发生了变化,但 max 缩放并再次停止工作。

原因是不更新参考。 什么是 ? 示例代码写为“需要更新引用”作为注释。 什么意思?

下面的示例代码调用:

xScale = chart.scales['newId'];

“newId”被重新分配为 scales id。

但我的是规模的最小值和最大值。 怎么样??

JSFillde

【问题讨论】:

    标签: javascript charts chart.js chartjs-plugin-zoom


    【解决方案1】:

    我想出了如何做到这一点。如果我知道,这没什么大不了的。

    回调函数updateChart()应该是这样的:

            function updateChart() {
                Chart.helpers.each(Chart.instances, function (instance) {
                    instance.options.scales.xAxes[0].time.min = leftEnd;
                    instance.options.scales.xAxes[0].time.max = rightEnd;              
                    instance.update();
                });
            }
    

    重点是我的数据是时间序列数据,因此比例选项应该使用“时间”。

    JSFillde 已更新。

    【讨论】:

    • 很好,但是 chart.js v3.2.1 怎么样?自上次附加 JSFiddle 以来似乎有一些不兼容的更改。
    • 发现如果将代码从“.xAxes[0].time.max”更改为“.x.max”,线性图表(v3.2.1)将起作用
    • 如果您还使用resetZoom() 重置您的缩放,它将不再起作用。你必须使用instance.options.scales.x.min = null; instance.options.scales.x.max = null; instance.update();
    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    相关资源
    最近更新 更多