I have a bar chart that I have scripted and am loading values in through my json file. All values appear through labels except for my highest value (60). What can I do to get my 60 label to appear in my chart?
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>CS50C Week11</title>
</head>
<body>
<div style="margin-top: 50px; padding:auto">
<canvas id="myCanvas" width="500" height="500" ></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
data.json
[25, 30, 40, 50, 35, 20, 45, 60, 55, 50]
script.js
try {
// Load data from JSON file
fetch('data.json')
.then(response => response.json())
.then(data => {
// Initialize canvas element
const canvas = document.getElementById('myCanvas');
if (!canvas) {
throw new Error('Canvas element not found');
}
const ctx = canvas.getContext('2d');
// Set chart properties
let chartWidth = 500;
let chartHeight = 500;
const barSpacing = 10;
const barWidth = (chartWidth - (data.length - 1) * barSpacing) / data.length;
const maxValue = Math.max(...data);
const labelFont = '16px Arial';
const valueFont = '12px Arial';
const labelColor = '#333';
const valueColor = '#999';
// Draw bars and labels
data.forEach((value, index) => {
const x = index * (barWidth + barSpacing);
const y = chartHeight - (value / maxValue) * chartHeight;
const height = (value / maxValue) * chartHeight;
// Draw bar
ctx.fillStyle = '#66a';
ctx.fillRect(x, y, barWidth, height);
// Draw label
ctx.font = labelFont;
ctx.fillStyle = labelColor;
ctx.textAlign = 'center';
ctx.fillText(` ${index + 1}`, x + barWidth / 2, chartHeight + 20);
// Draw value
ctx.font = valueFont;
ctx.fillStyle = valueColor;
ctx.textAlign = 'center';
ctx.fillText(value, x + barWidth / 2, y - 10);
});
})
.catch(error => console.log(error.message));
} catch (error) {
console.log(error.message);
}
I have tried adding this if condition in my Draw Label section of my JS
ctx.textAlign = 'center';
if (index === data.length - 1) {
// Adjust x-coordinate for last bar label
x += barWidth / 2;
}
so that way it only manipulates x under that condition, but doing so makes my bar furthest to the right disappear (in addition to my 60 bar already being gone)