0👍
You can use box annotations from chartjs-plugin-annotation
.
Please take a look at below runnable code and see how it works.
const rectangles = [
{ x: 2, y: 2, width: 8, height: 5 },
{ x: 2, y: 9, width: 8, height: 5 },
{ x: 2, y: 16, width: 8, height: 5 },
{ x: 2, y: 23, width: 8, height: 5 },
{ x: 12, y: 2, width: 5, height: 5 },
{ x: 12, y: 9, width: 12, height: 7 },
{ x: 25, y: 11, width: 8, height: 4 },
{ x: 18, y: 2, width: 8, height: 5 },
{ x: 16, y: 26, width: 16, height: 8 }
]
rectangles.forEach(r => {
r.type = 'box';
r.backgroundColor = 'rgba(0,180,0,0.02)';
r.borderColor = 'rgb(0,180,0)';
r.borderWidth = 1;
r.borderRadius = 4;
r.xMin = r.x;
r.yMin = r.y;
r.xMax = r.x + r.width;
r.yMax = r.y + r.height;
});
new Chart('myChart', {
type: 'scatter',
options: {
plugins: {
annotation: {
annotations: rectangles
}
},
scales: {
x: {
min: 0,
max: 35
},
y: {
min: 0,
max: 35
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.0.2/chartjs-plugin-annotation.min.js"></script>
<canvas id="myChart"></canvas>
Source:stackexchange.com