Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // stat.js
- 'use strict';
- window.renderStatistics = function (ctx, names, times) {
- // Выносим всё, что может быть повторно использовано в константы
- var HISTOGRAM_WIDTH = 40;
- var HISTOGRAM_HEIGHT = 150;
- var INITIAL_X = 150;
- var INITIAL_Y = 250;
- var COLUMN_INDENTATION = 50 + HISTOGRAM_WIDTH;
- var MY_HISTOGRAM_COLOR = 'rgba(255, 0, 0, 1)';
- var CHART_BG = 'white';
- var CHART_SHADOW = 'rgba(0, 0, 0, 0.7)';
- var FONT_COLOR = 'black';
- var FONT_SETUP = '16px PT Mono';
- var LABEL_OFFSET = 16;
- function getPlayerColor(name) {
- return (
- name.toLowerCase() === 'вы'
- ? MY_HISTOGRAM_COLOR
- : 'rgba(0, 0, 255, ' + Math.random() + ')'
- );
- }
- function drawHistogram(drawCtx, x, y, height, color) {
- drawCtx.fillStyle = color;
- drawCtx.fillRect(x, y, HISTOGRAM_WIDTH, -height);
- }
- function drawChartLabel(drawCtx, x, y, label) {
- drawCtx.fillStyle = FONT_COLOR;
- drawCtx.fillText(label, x, y);
- }
- ctx.font = FONT_SETUP;
- ctx.fillStyle = CHART_SHADOW;
- ctx.fillRect(110, 20, 420, 270);
- ctx.fillStyle = CHART_BG;
- ctx.strokeStyle = CHART_SHADOW;
- ctx.fillRect(100, 10, 420, 270);
- ctx.strokeRect(100, 10, 420, 270);
- ctx.fillStyle = FONT_COLOR;
- ctx.fillText('Ура, вы победили!', 120, 40);
- ctx.fillText('Список результатов:', 120, 60);
- var i;
- var step = 1;
- var colors = [];
- for (i = 0; i < times.length; i++) {
- var pendingStep = HISTOGRAM_HEIGHT / times[i];
- if (pendingStep < step) {
- step = pendingStep;
- }
- colors.push(getPlayerColor(names[i]));
- }
- // Тут я воспользовался forEach, т.к. на каждой итерации мы получаем функцию со своей областью видимости,
- // что позволяет нам сохранять промежуточные результаты и не засорять скоуп временными переменными.
- // Скорее всего предыдущий цикл я бы тоже так переписал :)
- colors.forEach(function (color, id) {
- var chartHeight = times[id] * step;
- var chartXOffset = INITIAL_X + COLUMN_INDENTATION * id;
- drawChartLabel(ctx, chartXOffset, INITIAL_Y + LABEL_OFFSET, names[id]);
- drawHistogram(ctx, chartXOffset, INITIAL_Y, chartHeight, color);
- drawChartLabel(ctx, chartXOffset, INITIAL_Y - chartHeight - LABEL_OFFSET, times[id].toFixed(0));
- });
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement