初学者快速入门:使用JavaScript简单实现条形图,饼图,折线图,玫瑰图,散点图

目录

数据结构设计

工具函数

图表实现细节

1. 条形图(Bar Chart)

2. 饼图(Pie Chart)

3. 玫瑰图(Rose Chart)

4. 折线图(Line Chart)

5. 散点图(Scatter Chart)

响应式处理

样式设计


整体架构

代码使用纯 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
    }))
};
  • labelsvalues用于大多数图表
  • 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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值