canvas-progress.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. Vue.component('canvas-progress', {
  2. template: '<canvas id="time-graph-canvas" width="100%" height="100%"></canvas>',
  3. props: ["progress"],
  4. data: function() {
  5. return {
  6. canvas:null,
  7. speed:0
  8. }
  9. },
  10. mounted: function () {
  11. this.canvas=document.getElementById("time-graph-canvas")
  12. this.drawMain(this.canvas, this.progress, "#12b7f5", "#bec8d2");
  13. },
  14. methods: {
  15. drawMain: function(drawing_elem, percent, forecolor, bgcolor) {
  16. /*
  17. @drawing_elem: 绘制对象
  18. @percent:绘制圆环百分比, 范围[0, 100]
  19. @forecolor: 绘制圆环的前景色,颜色代码
  20. @bgcolor: 绘制圆环的背景色,颜色代码
  21. */
  22. var context = drawing_elem.getContext("2d");
  23. var center_x = drawing_elem.width / 2;
  24. var center_y = drawing_elem.height / 2;
  25. var rad = Math.PI*2/100;
  26. var speed = this.speed;
  27. // 绘制背景圆圈
  28. function backgroundCircle(){
  29. context.save();
  30. context.beginPath();
  31. context.lineWidth = 8; //设置线宽
  32. var radius = center_x - context.lineWidth;
  33. context.lineCap = "round";
  34. context.strokeStyle = bgcolor;
  35. context.arc(center_x, center_y, radius, 0, Math.PI*2, false);
  36. context.stroke();
  37. context.closePath();
  38. context.restore();
  39. }
  40. //绘制运动圆环
  41. function foregroundCircle(n){
  42. context.save();
  43. context.strokeStyle = forecolor;
  44. context.lineWidth = 8;
  45. context.lineCap = "round";
  46. var radius = center_x - context.lineWidth;
  47. context.beginPath();
  48. context.arc(center_x, center_y, radius , -Math.PI/2, -Math.PI/2 +n*rad, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
  49. context.stroke();
  50. context.closePath();
  51. context.restore();
  52. }
  53. //绘制文字
  54. function text(n){
  55. context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
  56. context.fillStyle = forecolor;
  57. var font_size = 20;
  58. context.font = font_size + "px Helvetica";
  59. var number=n.toFixed(0);
  60. number=number>=100?100:number;
  61. var text_width = context.measureText(number+"%").width;
  62. context.fillText(number+"%", center_x-text_width/2, center_y + font_size/2);
  63. context.restore();
  64. }
  65. //执行动画
  66. (function drawFrame(){
  67. window.requestAnimationFrame(drawFrame);
  68. context.clearRect(0, 0, drawing_elem.width, drawing_elem.height);
  69. backgroundCircle();
  70. text(speed);
  71. foregroundCircle(speed);
  72. if(speed >= percent) return;
  73. speed += 1;
  74. }());
  75. }
  76. },watch:{
  77. progress:function(nval,oval){
  78. nval!=0 && (this.speed=oval);
  79. nval==0 && (this.speed=0);
  80. this.drawMain(this.canvas, nval, "#12b7f5", "#bec8d2");
  81. }
  82. }
  83. })