目录
整体架构
代码使用纯 JavaScript 和 Canvas API 实现了五种基本图表,采用模块化设计:
- 图表数据统一存储在
data对象中 - 使用
ChartUtils工具类封装通用方法 - 每种图表有独立的绘制函数
- 添加了响应式处理,支持窗口大小变化时重绘
数据结构设计
const data = {
labels: ['一月', '二月', '三月', '四月', '五月', '六月'],
values: [65, 59, 80, 81, 56, 55],
colors: ['#3B82F6', '#6366F1', '#8B5CF6', '#A855F7', '#C026D3', '#DB2777'],
scatterData: Array.from({length: 20}, () => ({
x: Math.random() * 300,
y: Math.random() * 200,
r: Math.random() * 10 + 5
}))
};
labels和values用于大多数图表colors定义了图表的配色方案scatterData为散点图生成随机数据点
工具函数
const ChartUtils = {
getColor: (index) => data.colors[index % data.colors.length],
drawLabel: (ctx, text, x, y, align = 'center') => {
ctx.save();
ctx.font = '12px Inter';
ctx.textAlign = align;
ctx.textBaseline = 'middle';
ctx.fillText(text, x, y);
ctx.restore();
}
};
getColor:循环使用预设颜色drawLabel:封装文本绘制逻辑,保存 / 恢复上下文状态避免样式冲突
图表实现细节
1. 条形图(Bar Chart)
function drawBarChart() {
// 计算边距和坐标系
const margin = {top: 20, right: 20, bottom: 40, left: 40};
const width = barChart.width - margin.left - margin.right;
const height = barChart.height - margin.top - margin.bottom;
const barWidth = width / data.labels.length * 0.7;
const maxValue = Math.max(...data.values) * 1.1;
// 绘制坐标轴
barCtx.beginPath();
barCtx.moveTo(margin.left, margin.top);
barCtx.lineTo(margin.left, margin.top + height);
barCtx.lineTo(margin.left + width, margin.top + height);
barCtx.strokeStyle = '#ccc';
barCtx.stroke();
// 绘制条形和标签
data.values.forEach((value, index) => {
// 计算条形位置和高度
const barHeight = (value / maxValue) * height;
const x = margin.left + (width / data.labels.length) * index + (width / data.labels

最低0.47元/天 解锁文章
542

被折叠的 条评论
为什么被折叠?



