Licitator 1.0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.4 KiB

5 years ago
  1. window.onload = function(){
  2. //canvas initialization
  3. var canvas = document.getElementById("canvas");
  4. var ctx = canvas.getContext("2d");
  5. //dimensions
  6. var W = canvas.width;
  7. var H = canvas.height;
  8. //Variables
  9. var degrees = 0;
  10. var new_degrees = 0;
  11. var difference = 0;
  12. var color = "#b2c831"; //green looks better to me
  13. var bgcolor = "#222";
  14. var text;
  15. var animation_loop, redraw_loop;
  16. function init()
  17. {
  18. //Clear the canvas everytime a chart is drawn
  19. ctx.clearRect(0, 0, W, H);
  20. //Background 360 degree arc
  21. ctx.beginPath();
  22. ctx.strokeStyle = bgcolor;
  23. ctx.lineWidth = 30;
  24. ctx.arc(W/2, H/2, 100, 0, Math.PI*2, false); //you can see the arc now
  25. ctx.stroke();
  26. //gauge will be a simple arc
  27. //Angle in radians = angle in degrees * PI / 180
  28. var radians = degrees * Math.PI / 180;
  29. ctx.beginPath();
  30. ctx.strokeStyle = color;
  31. ctx.lineWidth = 30;
  32. //The arc starts from the rightmost end. If we deduct 90 degrees from the angles
  33. //the arc will start from the topmost end
  34. ctx.arc(W/2, H/2, 100, 0 - 90*Math.PI/180, radians - 90*Math.PI/180, false);
  35. //you can see the arc now
  36. ctx.stroke();
  37. //Lets add the text
  38. ctx.fillStyle = color;
  39. ctx.font = "50px open sans";
  40. text = Math.floor(degrees/360*100) + "%";
  41. //Lets center the text
  42. //deducting half of text width from position x
  43. text_width = ctx.measureText(text).width;
  44. //adding manual value to position y since the height of the text cannot
  45. //be measured easily. There are hacks but we will keep it manual for now.
  46. ctx.fillText(text, W/2 - text_width/2, H/2 + 15);
  47. }
  48. function draw()
  49. {
  50. //Cancel any movement animation if a new chart is requested
  51. if(typeof animation_loop != undefined) clearInterval(animation_loop);
  52. //random degree from 0 to 360
  53. new_degrees = Math.round(Math.random()*360);
  54. difference = new_degrees - degrees;
  55. //This will animate the gauge to new positions
  56. //The animation will take 1 second
  57. //time for each frame is 1sec / difference in degrees
  58. animation_loop = setInterval(animate_to, 1000/difference);
  59. }
  60. //function to make the chart move to new degrees
  61. function animate_to()
  62. {
  63. //clear animation loop if degrees reaches to new_degrees
  64. if(degrees == new_degrees)
  65. clearInterval(animation_loop);
  66. if(degrees < new_degrees)
  67. degrees++;
  68. else
  69. degrees--;
  70. init();
  71. }
  72. //Lets add some animation for fun
  73. draw();
  74. redraw_loop = setInterval(draw, 2000); //Draw a new chart every 2 seconds
  75. }