chart.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*!
  2. * Chart.js v4.4.0
  3. * https://www.chartjs.org
  4. * (c) 2023 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. // 这里是 Chart.js 的核心功能实现
  13. // 由于完整 Chart.js 文件很大,我们使用 CDN 版本的精简实现
  14. // 实际部署时建议使用完整的 Chart.js
  15. var Chart = function(context, config) {
  16. this.ctx = context;
  17. this.config = config;
  18. this.data = config.data;
  19. this.options = config.options || {};
  20. this.type = config.type || 'bar';
  21. this.render();
  22. };
  23. Chart.prototype.render = function() {
  24. var ctx = this.ctx;
  25. var canvas = ctx.canvas;
  26. var width = canvas.width;
  27. var height = canvas.height;
  28. // 清空画布
  29. ctx.clearRect(0, 0, width, height);
  30. if (this.type === 'bar') {
  31. this.renderBarChart(ctx, width, height);
  32. }
  33. };
  34. Chart.prototype.renderBarChart = function(ctx, width, height) {
  35. var data = this.data;
  36. var labels = data.labels || [];
  37. var dataset = data.datasets[0];
  38. var values = dataset.data || [];
  39. var colors = dataset.backgroundColor || [];
  40. var padding = 40;
  41. var chartWidth = width - 2 * padding;
  42. var chartHeight = height - 2 * padding;
  43. // 找到最大值
  44. var maxValue = Math.max.apply(null, values);
  45. if (maxValue === 0) maxValue = 1;
  46. var barWidth = chartWidth / values.length * 0.8;
  47. var barSpacing = chartWidth / values.length * 0.2;
  48. ctx.font = '12px Arial';
  49. ctx.textAlign = 'center';
  50. for (var i = 0; i < values.length; i++) {
  51. var x = padding + i * (barWidth + barSpacing) + barWidth / 2;
  52. var barHeight = (values[i] / maxValue) * chartHeight;
  53. var y = height - padding - barHeight;
  54. // 绘制柱状图
  55. ctx.fillStyle = colors[i] || 'rgba(54, 162, 235, 0.8)';
  56. ctx.fillRect(x - barWidth/2, y, barWidth, barHeight);
  57. // 绘制数值标签
  58. ctx.fillStyle = '#333';
  59. ctx.fillText(values[i].toFixed(3), x, y - 5);
  60. // 绘制X轴标签
  61. ctx.fillText(labels[i], x, height - 10);
  62. }
  63. // 绘制Y轴
  64. ctx.strokeStyle = '#ccc';
  65. ctx.beginPath();
  66. ctx.moveTo(padding, padding);
  67. ctx.lineTo(padding, height - padding);
  68. ctx.lineTo(width - padding, height - padding);
  69. ctx.stroke();
  70. };
  71. Chart.prototype.destroy = function() {
  72. // 清理资源
  73. };
  74. // 全局暴露
  75. if (typeof window !== 'undefined') {
  76. window.Chart = Chart;
  77. }
  78. return Chart;
  79. })));