canvas-ring.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. var windWidth = wx.getSystemInfoSync().windowWidth;
  2. Component({
  3. options: {
  4. multipleSlots: true // 在组件定义时的选项中启用多slot支持
  5. },
  6. /**
  7. * 组件的属性列表
  8. */
  9. properties: {
  10. //画布的宽度 默认占屏幕宽度的0.4倍
  11. canvasWidth: {
  12. type: Number,
  13. value: windWidth * 0.4
  14. },
  15. //线条宽度 默认10
  16. lineWidth: {
  17. type: Number,
  18. value: 10
  19. },
  20. //线条颜色 默认"#393"
  21. lineColor: {
  22. type: String,
  23. value: "#393"
  24. },
  25. //标题 默认“完成率”
  26. title: {
  27. type: String,
  28. value: "完成率"
  29. },
  30. //当前的值 默认45
  31. value: {
  32. type: Number,
  33. value: 45
  34. },
  35. //值的颜色 默认"#ff9c07"
  36. valueColor: {
  37. type: String,
  38. value: "#696969"
  39. },
  40. //最大值 默认100
  41. maxValue: {
  42. type: Number,
  43. value: 100
  44. },
  45. //最小值 默认0
  46. minValue: {
  47. type: Number,
  48. value: 0
  49. },
  50. //当前值的后缀名
  51. suffix: {
  52. type: null,
  53. value: "%"
  54. },
  55. //从什么角度开始 0~360之间 (12点方向为0,18点方向为180,0点方向为360)
  56. startDegree: {
  57. type: Number,
  58. value: 0
  59. },
  60. //外圆颜色
  61. borderColor: {
  62. type: String,
  63. value: '#eee',
  64. },
  65. },
  66. /**
  67. * 组件的初始数据
  68. */
  69. data: {
  70. canvasWidth: windWidth * 0.4,
  71. isMarginTop: true
  72. },
  73. /**
  74. * 组件的方法列表
  75. */
  76. methods: {
  77. showCanvasRing() {
  78. //去掉首位空格后如果标题为空,那么当前值的区域就没有margin-top值
  79. if (this.data.title.replace(/(^\s*)|(\s*$)/g, "").length == 0) {
  80. this.setData({
  81. isMarginTop: false
  82. })
  83. }
  84. //作画
  85. var ctx = wx.createCanvasContext("circleBar", this); //canvas组建封装,需要后加个this
  86. var circle_r = this.data.canvasWidth / 2; //画布的一半,用来找中心点和半径
  87. var startDegree = this.data.startDegree; //从什么角度开始
  88. var maxValue = this.data.maxValue; //最大值
  89. var minValue = this.data.minValue; //最小值
  90. var value = this.data.value; //当前的值
  91. var lineColor = this.data.lineColor; //线条颜色
  92. var lineWidth = this.data.lineWidth; //线条宽度
  93. var percent = 360 * ((value - minValue) / (maxValue - minValue)); //计算结果
  94. //定义起始点
  95. ctx.translate(circle_r, circle_r);
  96. //灰色圆弧
  97. ctx.beginPath();
  98. ctx.setStrokeStyle("#ebebeb");
  99. ctx.setLineWidth(lineWidth);
  100. ctx.arc(0, 0, circle_r - 10, 0, 2 * Math.PI, true);
  101. ctx.stroke();
  102. ctx.closePath();
  103. //有色彩的圆弧
  104. ctx.beginPath();
  105. ctx.setStrokeStyle(lineColor);
  106. ctx.setLineWidth(lineWidth);
  107. ctx.arc(0, 0, circle_r - 10, startDegree * Math.PI / 180 - 0.5 * Math.PI, percent * Math.PI / 180 + startDegree * Math.PI / 180 - 0.5 * Math.PI, false);
  108. ctx.stroke();
  109. ctx.closePath();
  110. ctx.draw();
  111. }
  112. }
  113. })