drawGraph.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. export const drawCircle = (domId: string, type: number, rateNum: number) => {
  2. const colorObj = type === 1 ?{
  3. start: '#279FFE',
  4. end: '#43C8FE',
  5. bg: '#D9EEFF',
  6. textColor: '#259CFE',
  7. } : {
  8. start: '#24BD90',
  9. end: '#7CE3C5',
  10. bg: '#E8F6F2',
  11. textColor: '#24BD90',
  12. }
  13. // 获取canvas元素和上下文
  14. const canvas: any = document.getElementById(domId);
  15. const ctx = canvas.getContext('2d');
  16. // 设置百分比(0-100)
  17. const percentage = rateNum || 0;
  18. // 圆环的设置
  19. const radius = 30; // 圆环半径
  20. const lineWidth = 8; // 圆环的宽度
  21. // 圆心坐标
  22. const centerX = canvas.width / 2;
  23. const centerY = canvas.height / 2;
  24. // 创建渐变色
  25. function createGradient() {
  26. const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
  27. gradient.addColorStop(0, colorObj.start); // 渐变开始颜色
  28. gradient.addColorStop(1, colorObj.end); // 渐变结束颜色
  29. return gradient;
  30. }
  31. // 绘制背景圆环
  32. function drawBackgroundCircle() {
  33. ctx.beginPath();
  34. ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
  35. ctx.lineWidth = lineWidth;
  36. ctx.strokeStyle = colorObj.bg; // 背景圆环的颜色
  37. ctx.lineJoin = 'round'; // 设置圆角效果
  38. ctx.stroke();
  39. }
  40. // 绘制进度圆环
  41. function drawProgressCircle() {
  42. const startAngle = -0.5 * Math.PI; // 起始角度,从顶部开始
  43. const endAngle = (percentage / 100) * 2 * Math.PI - 0.5 * Math.PI; // 结束角度,按照百分比计算
  44. ctx.beginPath();
  45. ctx.arc(centerX, centerY, radius, startAngle, endAngle);
  46. ctx.lineWidth = lineWidth;
  47. ctx.strokeStyle = createGradient(); // 进度圆环使用渐变色
  48. ctx.lineJoin = 'round'; // 设置圆角效果
  49. ctx.stroke();
  50. }
  51. // 绘制百分比文本
  52. function drawText() {
  53. ctx.font = '18px DIN';
  54. ctx.fillStyle = colorObj.textColor;
  55. ctx.textAlign = 'center';
  56. ctx.textBaseline = 'middle';
  57. ctx.fillText(percentage + '%', centerX, centerY-6); // 绘制百分比文本
  58. }
  59. // 清除文本区域
  60. function clearTextArea() {
  61. const textWidth = ctx.measureText(percentage + '%').width; // 获取文本宽度
  62. const padding = 10; // 给文本区域留一些边距
  63. // 清除文本区域的矩形区域
  64. ctx.clearRect(centerX - textWidth / 2 - padding, centerY - 24 - padding, textWidth + padding * 2, 48);
  65. }
  66. clearTextArea();
  67. drawBackgroundCircle(); // 绘制背景圆环
  68. drawProgressCircle(); // 绘制进度圆环
  69. drawText();
  70. }