酷代码 AI
菜单
服务商

<!DOCTYPE html> <html> <head> <title>香烟价格需求弹性折线图</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <!-- 图表容器,设置居中且合适宽度 --> <div style="width: 70%; margin: 20px auto;"> <canvas id="cigaretteElasticityChart"></canvas> </div> <script> // 获取画布上下文 const ctx = document.getElementById('cigaretteElasticityChart').getContext('2d'); // 创建折线图实例 new Chart(ctx, { type: 'line', // 明确指定为折线图

这段代码整体功能实现良好,能够正确绘制出不同消费群体对香烟价格的需求弹性折线图。不过有一些可以优化的地方: 优化建议 1. CSS 分离:将内联样式提取到外部 CSS 文件或者 `<style>` 标签中,提高代码的可维护性。 2. 变量命名:可以将一些配置数据提取为常量,提高代码的可读性。 3. 错误处理:添加对 `getElementById` 返回值的检查,确保元素存在。 优化后的代码 ```html <!DOCTYPE html> <html> <head> <title>香烟价格需求弹性折线图</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> /* 图表容器样式 */ .chart-container { width: 70%; margin: 20px auto; } </style> </head> <body> <!-- 图表容器 --> <div class="chart-container"> <canvas id="cigaretteElasticityChart"></canvas> </div> <script> // 定义常量 const CHART_ID = 'cigaretteElasticityChart'; const LABELS = ["青少年", "低收入成年吸烟者", "中收入成年吸烟者", "高收入成年吸烟者"]; const DATA = [4.5, 4.0, 2.5, 1.5]; const BORDER_COLOR = '#2c3e50'; const BACKGROUND_COLOR = 'rgba(44, 62, 80, 0.1)'; // 获取画布上下文并检查元素是否存在 const canvas = document.getElementById(CHART_ID); if (canvas) { const ctx = canvas.getContext('2d'); // 创建折线图实例 new Chart(ctx, { type: 'line', data: { labels: LABELS, datasets: [{ label: "需求弹性系数(绝对值)", data: DATA, borderColor: BORDER_COLOR, backgroundColor: BACKGROUND_COLOR, borderWidth: 2, pointRadius: 5, pointHoverRadius: 7, tension: 0.2, fill: false }] }, options: { responsive: true, plugins: { title: { display: true, text: "不同消费群体对香烟价格的需求弹性趋势", font: { size: 18, weight: 'bold' }, padding: { bottom: 20 } }, legend: { display: true, position: 'top', labels: { font: { size: 12 } } } }, scales: { y: { beginAtZero: true, max: 5, title: { display: true, text: "需求弹性系数(绝对值)", font: { size: 14 } }, ticks: { stepSize: 1 } }, x: { title: { display: true, text: "消费群体类型", font: { size: 14 } } } } } }); } else { console.error(`未找到 ID 为 ${CHART_ID} 的元素`); } </script> </body> </html> ``` 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. 当使用外部脚本库时,要确保脚本的加载顺序正确,避免因依赖问题导致图表无法正常显示。 2. 在设置图表的尺寸和响应式布局时,要考虑不同设备和屏幕分辨率的兼容性,避免图表显示异常。 3. 对于动态数据更新的情况,要注意更新数据后调用 `chart.update()` 方法来刷新图表,否则图表不会实时更新。 [2025-09-06 17:56:09 | AI写代码神器 | 929点数解答]

相关提问
聚合导航,免费问AI
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]