Search code examples
angularchart.jsangular7

How to zoom charts in chart.js using angular 7


I have a line-chart and I want to zoom it but unable to do it. Here is my code

let ctx = document.getElementById('myChart')

let chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [7, 10, 3, 5, 2, 3],
          fill: true,
          backgroundColor: 'orange',
          borderColor: 'green',
          pointBorderColor: 'red',
          pointBackgroundColor: 'red'
        }]
      },
      options: {
        plugins: {
          pan: {
            enabled: true,
            mode: 'x',
            onPan: function () { console.log('I was panned!!!'); }
          },
          zoom: {
            enabled: true,
            drag: true,
            mode: 'x',
            onZoom: function () { console.log('I was zoomed!!!'); }
          },
        },
        responsive: true,
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>

<div class="row">
    <div class="col d-flex justify-content-center">
        <canvas id="myChart" style="max-width:95%;height:300px !important;"></canvas>
    </div>
</div>

I have used the following plugin for zooming

https://github.com/chartjs/chartjs-plugin-zoom#readme

I have also included hammerjs and angular/animations in my project.

Update

Why pan and zoom are unknown to typescript?

// package.json
"chart.js": "^2.7.3",
"chartjs-plugin-zoom": "^0.6.6",

enter image description here


Solution

  • First you need to Run npm install chartjs-plugin-zoom to install with npm then do import chartjs-plugin-zoom in your .ts file and write plugin like this :

        plugins: {
          zoom: {
            pan: {
              enabled: true,
              mode: 'x'
            },
            zoom: {
              enabled: true,
              mode: 'x'
            }
          }
        },