ChartJS折线图拖放

时间:2018-04-24 14:49:28

标签: javascript python django chart.js linechart

是否可以在ChartJS上添加拖动和缩放功能?我想做类似here的事情。

以下是我绘制折线图的方法:

<canvas class="square_margin_less" id="myChart" width="100" height="30" > </canvas>
<script>
new Chart(document.getElementById("myChart").getContext('2d'),
{
    type: 'line',
    data: {
        labels: {{ data.labels|safe }},
        datasets:
        [{
            label: 'x',
            data: {{ data.x }},
            borderColor: 'rgba(233,105,118,1)',
        },
        {
            label: 'y',
            data: {{ data.y }},
            borderColor: 'rgba(96,143,239,1)'
        },
        {
            label: 'z',
            data: {{ data.z }},
            borderColor: 'rgba(144,247,136,1)'
        }]
    },
});
</script>

有一些个性化的方法吗?

1 个答案:

答案 0 :(得分:1)

我没有找到Chart.js的“拖动和缩放”功能,也没有找到带有“平移和缩放”版本的简单示例,因此我决定自己实现演示版。

外部脚本列表非常重要:hammer-js,然后是Chart.bundle.jschartjs-plugin-zoom.js

const config = {
  type: 'line',
  data: {
    labels: [new Date('2019-08-20'), new Date('2019-08-25'), new Date('2019-08-30')],
    datasets: [{
      label: 'Line',
      data: [2, 5, 3],
      borderColor: '#D4213D',
      fill: false,
    }, ],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
      }, ],
    },
    pan: {
      enabled: true,
      mode: 'xy',
    },
    zoom: {
      enabled: true,
      mode: 'xy', // or 'x' for "drag" version
    },
  },
};

window.onload = function() {
  new Chart(document.getElementById('chart'), config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.6.6/chartjs-plugin-zoom.js"></script>
<html>
<body>
  <div style="width:380px;">
    <canvas id="chart"></canvas>
  </div>
</body>
</html>

如果有人对其他图书馆感兴趣,我在Vicotry网站上找到了一种有趣的解决方案,该解决方案具有折线图的“画笔和缩放”功能:https://formidable.com/open-source/victory/guides/brush-and-zoom/

编辑:在“拖动”版本中,您将不得不使用缩放:

drag: {
   borderColor: 'hsl(35, 100%, 60%)',
   borderWidth: '3',
   backgroundColor: 'hsl(35, 100%, 60%)',
},