@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 2 |
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation"></script> |
1
|
<canvas id="myChart"></canvas> |
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
).
That's it! You should now have a rectangle displayed in your Chart.js chart.