How to make rectangle in chart.js?

Member

by lew , in category: Javascript , 9 months ago

How to make rectangle in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 months ago

@lew 

To make a rectangle in Chart.js, you can use the "Rectangle Annotation" plugin provided by Chart.js. Here is a step-by-step guide:

  1. First, you need to include the necessary Chart.js files in your HTML. You can do this by including the following scripts in the section of your HTML file:
1
2
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation"></script>


  1. Create a canvas element in your HTML where you want to display the chart:
1
<canvas id="myChart"></canvas>


  1. Create a JavaScript function to generate the chart and define the rectangle annotation:
 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
30
31
function createChart() {
  // Get the canvas element
  var canvas = document.getElementById('myChart');

  // Generate the chart
  var chart = new Chart(canvas, {
    type: 'line',
    data: {
      // Put your chart data here
    },
    options: {
      annotation: {
        drawTime: 'beforeDatasetsDraw',
        annotations: [
          {
            type: 'box',
            xMin: 1,
            xMax: 2,
            yMin: 3,
            yMax: 4,
            backgroundColor: 'rgba(255, 0, 0, 0.5)' // Define the color and transparency of the rectangle
          }
        ]
      },
      // Other chart options
    }
  });
}

// Call the createChart function to generate the chart
createChart();


In the above example, the rectangle annotation is defined within the options object using the annotation property. The annotations property takes an array of annotation objects. Each annotation object defines the type of annotation (in this case, 'box' for a rectangle), the x and y positions of the rectangle (using xMin, xMax, yMin, yMax), and the background color (backgroundColor).

  1. Customize the rectangle and insert your own data and chart options as needed.


That's it! You should now have a rectangle displayed in your Chart.js chart.