使用Chart.js在水平堆叠的条形图中显示一段时间内的进度,可以按照以下步骤进行操作:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
const progressData = [
{ time: "2022-01-01", progress: 20 },
{ time: "2022-02-01", progress: 40 },
{ time: "2022-03-01", progress: 60 },
{ time: "2022-04-01", progress: 80 },
{ time: "2022-05-01", progress: 100 }
];
function processData(data) {
const labels = [];
const values = [];
data.forEach(item => {
const time = new Date(item.time);
const formattedTime = time.toLocaleDateString("en-US", { month: "short", year: "numeric" });
labels.push(formattedTime);
values.push(item.progress);
});
return { labels, values };
}
processData
函数,将进度数据转换为适用于Chart.js的格式:const processedData = processData(progressData);
const chartConfig = {
type: "horizontalBar",
data: {
labels: processedData.labels,
datasets: [{
label: "Progress",
data: processedData.values,
backgroundColor: "rgba(75, 192, 192, 0.5)"
}]
},
options: {
scales: {
x: {
stacked: true,
beginAtZero: true
},
y: {
stacked: true
}
}
}
};
const ctx = document.getElementById("progressChart").getContext("2d");
new Chart(ctx, chartConfig);
完整的HTML文件示例代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Progress Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="progressChart" width="400" height="200"></canvas>
<script>
const progressData = [
{ time: "2022-01-01", progress: 20 },
{ time: "2022-02-01", progress: 40 },
{ time: "2022-03-01", progress: 60 },
{ time: "2022-04-01", progress: 80 },
{ time: "2022-05-01", progress: 100 }
];
function processData(data) {
const labels = [];
const values = [];
data.forEach(item => {
const time = new Date(item.time);
const formattedTime = time.toLocaleDateString("en-US", { month: "short", year: "numeric" });
labels.push(formattedTime);
values.push(item.progress);
});
return { labels, values };
}
const processedData = processData(progressData);
const chartConfig = {
type: "horizontalBar",
data: {
labels: processedData.labels,
datasets: [{
label: "Progress",
data: processedData.values,
backgroundColor: "rgba(75, 192, 192, 0.5)"
}]
},
options: {
scales: {
x: {
stacked: true,
beginAtZero: true
},
y: {
stacked: true
}
}
}
};
const ctx = document.getElementById("progressChart").getContext("2d");
new Chart(ctx, chartConfig);
</script>
</body>
</html>
这样就可以使用Chart.js在水平堆叠的条形图中显示一段时间内的进度。请注意,本答案中没有提及腾讯云相关产品,因为此问题与云计算提供商无关。如果需要腾讯云相关产品的信息,请参考腾讯云官方文档或联系腾讯云客服获取相关信息。
领取专属 10元无门槛券
手把手带您无忧上云