How to add a vertical cursor line in chart.js?

Member

by dana , in category: Javascript , 5 months ago

How to add a vertical cursor line in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 5 months ago

@dana 

To add a vertical cursor line in Chart.js, you can use the annotation plugin provided by Chart.js. Here are the steps to add a vertical cursor line:

  1. Create a div element to wrap your chart canvas and give it a unique ID. For example:
1
2
3
<div id="chartWrapper">
  <canvas id="myChart"></canvas>
</div>


  1. Include the Chart.js library and the annotation plugin in your HTML document.
1
2
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>


  1. Add the JavaScript code to create your chart and add the vertical cursor line using the annotation plugin.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Get the chart canvas element
var chartCanvas = document.getElementById('myChart');

// Create the chart
var chart = new Chart(chartCanvas, {
  type: 'line',
  data: {
    // Your chart data
  },
  options: {
    // Your chart options
    annotation: {
      // Add the vertical line annotation
      drawTime: 'afterDraw',
      annotations: [{
        type: 'line',
        mode: 'vertical',
        scaleID: 'x-axis-0',
        value: '2021-01-01', // Set the date or X-axis value where you want to add the line
        borderColor: 'red',
        borderWidth: 2,
        label: {
          enabled: true,
          content: 'Cursor Line'
        }
      }]
    }
  }
});


In the code above, you need to replace '2021-01-01' with the specific date or X-axis value where you want to add the vertical cursor line. You can customize the line color, width, and label according to your needs.

  1. Finally, add CSS to style the chart wrapper and make it position relative to ensure the cursor line is displayed correctly.
1
2
3
#chartWrapper {
  position: relative;
}


That's it! With these steps, you should be able to add a vertical cursor line to your Chart.js chart.