hangban/main.js

78 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Chart from 'chart.js/auto'
const rest = await fetch('http://localhost:2000/api').then(res => res.json())
const table = document.createElement('table')
// 添加表头
const thead = document.createElement('thead')
const tr = document.createElement('tr')
for (let key in rest[0]) {
const th = document.createElement('th')
th.textContent = key
tr.appendChild(th)
}
thead.appendChild(tr)
table.appendChild(thead)
// 添加数据
for (let row of rest) {
const tr = document.createElement('tr')
for (let key in row) {
const td = document.createElement('td')
td.textContent = row[key]
tr.appendChild(td)
}
table.appendChild(tr)
}
// 写入页面
document.body.appendChild(table)
// 生成随机数据
function generateRandomData(num, minPrice, maxPrice) {
const data = [];
const today = new Date();
for (let i = 0; i < num; i++) {
const randomDays = Math.floor(Math.random() * 30); // 随机天数
const newDate = new Date(today.getTime() + randomDays * 24 * 60 * 60 * 1000); // 增加随机天数
const price = Math.floor(Math.random() * (maxPrice - minPrice + 1)) + minPrice; // 随机价格
data.push({
date: newDate.toISOString().split('T')[0], // 格式化为 YYYY-MM-DD
price: price
});
}
return data;
}
// 生成 10 条随机数据
const numEntries = 10;
const data = generateRandomData(numEntries, 100, 500);
// 创建图表
const ctx = document.createElement('canvas');
document.body.appendChild(ctx);
new Chart(ctx, {
type: 'line',
data: {
labels: data.map(row => row.date),
datasets: [{
label: '航班价格',
data: data.map(row => row.price),
backgroundColor: 'rgba(255, 99, 132, 0.2)', // 曲线下方填充颜色透明度0.2
borderColor: 'rgba(255, 99, 132, 1)', // 曲线颜色
borderWidth: 2, // 曲线宽度
lineTension: 0.3, // 平滑曲线
fill: true // 填充曲线下方区域
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});