Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. // stat.js
  2. 'use strict';
  3.  
  4. window.renderStatistics = function (ctx, names, times) {
  5. // Выносим всё, что может быть повторно использовано в константы
  6. var HISTOGRAM_WIDTH = 40;
  7. var HISTOGRAM_HEIGHT = 150;
  8. var INITIAL_X = 150;
  9. var INITIAL_Y = 250;
  10. var COLUMN_INDENTATION = 50 + HISTOGRAM_WIDTH;
  11. var MY_HISTOGRAM_COLOR = 'rgba(255, 0, 0, 1)';
  12. var CHART_BG = 'white';
  13. var CHART_SHADOW = 'rgba(0, 0, 0, 0.7)';
  14. var FONT_COLOR = 'black';
  15. var FONT_SETUP = '16px PT Mono';
  16. var LABEL_OFFSET = 16;
  17.  
  18. function getPlayerColor(name) {
  19. return (
  20. name.toLowerCase() === 'вы'
  21. ? MY_HISTOGRAM_COLOR
  22. : 'rgba(0, 0, 255, ' + Math.random() + ')'
  23. );
  24. }
  25.  
  26. function drawHistogram(drawCtx, x, y, height, color) {
  27. drawCtx.fillStyle = color;
  28. drawCtx.fillRect(x, y, HISTOGRAM_WIDTH, -height);
  29. }
  30.  
  31. function drawChartLabel(drawCtx, x, y, label) {
  32. drawCtx.fillStyle = FONT_COLOR;
  33. drawCtx.fillText(label, x, y);
  34. }
  35.  
  36. ctx.font = FONT_SETUP;
  37.  
  38. ctx.fillStyle = CHART_SHADOW;
  39. ctx.fillRect(110, 20, 420, 270);
  40.  
  41. ctx.fillStyle = CHART_BG;
  42. ctx.strokeStyle = CHART_SHADOW;
  43. ctx.fillRect(100, 10, 420, 270);
  44. ctx.strokeRect(100, 10, 420, 270);
  45.  
  46. ctx.fillStyle = FONT_COLOR;
  47. ctx.fillText('Ура, вы победили!', 120, 40);
  48. ctx.fillText('Список результатов:', 120, 60);
  49.  
  50. var i;
  51. var step = 1;
  52. var colors = [];
  53.  
  54. for (i = 0; i < times.length; i++) {
  55. var pendingStep = HISTOGRAM_HEIGHT / times[i];
  56. if (pendingStep < step) {
  57. step = pendingStep;
  58. }
  59.  
  60. colors.push(getPlayerColor(names[i]));
  61. }
  62.  
  63. // Тут я воспользовался forEach, т.к. на каждой итерации мы получаем функцию со своей областью видимости,
  64. // что позволяет нам сохранять промежуточные результаты и не засорять скоуп временными переменными.
  65. // Скорее всего предыдущий цикл я бы тоже так переписал :)
  66. colors.forEach(function (color, id) {
  67. var chartHeight = times[id] * step;
  68. var chartXOffset = INITIAL_X + COLUMN_INDENTATION * id;
  69.  
  70. drawChartLabel(ctx, chartXOffset, INITIAL_Y + LABEL_OFFSET, names[id]);
  71. drawHistogram(ctx, chartXOffset, INITIAL_Y, chartHeight, color);
  72. drawChartLabel(ctx, chartXOffset, INITIAL_Y - chartHeight - LABEL_OFFSET, times[id].toFixed(0));
  73. });
  74. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement