ProcentPeriodTimer

ProcentPeriodTimer
Anonymous
JavaScript
11/28/2026 8:41 PM
25.0 KB
8
Indexable
Never
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ProcentPeriodTimer</title>
<style>
  :root{
    --bg: #0f1720;
    --card-bg: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01));
    --border: rgba(255,255,255,0.04);
    --primary: #06b6d4;        /* меняется из JS синхронно с бубликом */
    --on-primary: #0f1720;     /* цвет текста на кнопке, подбирается из JS */
    --muted: #9aa4b2;
    --white: #e6eef6;
    --mono: #cbd5e1;
    --table-bg: rgba(255,255,255,0.02);
    --table-border: rgba(255,255,255,0.03);
    --hover: #e3c353;
  }
  *{ box-sizing: border-box; }
  body{
    margin: 0;
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg);
    font-family: "Segoe UI", Roboto, Arial, sans-serif;
    color: var(--white);
  }
  .app{
    width: 350px;
    min-height: 520px;
    background: var(--card-bg);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    box-shadow: 0 10px 30px rgba(0,0,0,.5);
    overflow: hidden;
  }
  h1{
    margin: 0;
    max-width: 100%;
    min-height: 22px;
    font-size: 18px;
    line-height: 22px;
    text-align: center;
    white-space: nowrap;
    letter-spacing: .5px;
    color: var(--white);
  }
  .field{
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 4px;
    font-size: 12px;
    color: var(--muted);
  }
  .field input{
    width: 100%;
    padding: 7px 10px;
    border: 1px solid var(--border);
    border-radius: 8px;
    background: var(--table-bg);
    color: var(--white);
    font-size: 14px;
    color-scheme: dark;
    outline: none;
    transition: border-color .2s;
  }
  .field input:hover,
  .field input:focus{ border-color: var(--hover); }

  canvas{
    width: 240px;
    height: 240px;
    cursor: pointer;
    flex-shrink: 0;
  }
  .hint{
    font-size: 11px;
    color: var(--muted);
    margin-top: -4px;
  }

  /* Оставшиеся секунды — цвет синхронизирован с бубликом и кнопкой */
  #secondsRemaining{
    width: 100%;
    min-height: 20px;
    line-height: 20px;
    text-align: center;
    white-space: nowrap;
    font-family: Consolas, "Courier New", monospace;
    font-size: 15px;
    font-weight: 700;
    color: var(--primary);
    transition: color .2s;
  }

  table{
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    background: var(--table-bg);
    border: 1px solid var(--table-border);
    border-radius: 10px;
    overflow: hidden;
    font-size: 12.5px;
  }
  td{
    padding: 7px 10px;
    border-bottom: 1px solid var(--table-border);
    vertical-align: top;
  }
  tr:last-child td{ border-bottom: none; }
  td.label{
    width: 82px;
    color: var(--muted);
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: .5px;
    padding-top: 9px;
  }
  td.value{
    color: var(--mono);
    font-family: Consolas, "Courier New", monospace;
    line-height: 1.35;
  }
  table.alert td.label,
  table.alert td.value{ color: #ff6b73; }

  button{
    width: 100%;
    margin-top: auto;
    padding: 10px;
    border: none;
    border-radius: 10px;
    background: var(--primary);
    color: var(--on-primary);
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    transition: background .2s, color .2s;
  }
  button:hover{ background: var(--hover); color: var(--bg); }
</style>
</head>
<body>

<div class="app">
  <h1 id="title"></h1>

  <label class="field">
    Конечная дата и время
    <input type="datetime-local" id="endInput" step="1">
  </label>

  <canvas id="donut"></canvas>
  <div class="hint" id="hint"></div>

  <!-- общее количество оставшихся секунд с правильным склонением и разделителем разрядов -->
  <div id="secondsRemaining"></div>

  <table id="infoTable">
    <tr>
      <td class="label">Прошло:</td>
      <td class="value" id="elapsed"></td>
    </tr>
    <tr>
      <td class="label" id="remLabel">Осталось:</td>
      <td class="value" id="remaining"></td>
    </tr>
  </table>

  <button id="saveBtn">Сохранить PNG</button>
</div>

<script>
(() => {
  'use strict';

  // ---------- Настройки ----------
  const RED = '#dd000d';
  const DEFAULT_COLOR = '#06b6d4';
  const ALERT_TEXT = '#ff6b73';
  const LS_END = 'ppt_end';
  const LS_COLOR = 'ppt_color';
  const LS_HUE = 'ppt_hue';

  const SIZE = 240;   // CSS-размер canvas с бубликом
  const LINE = 26;    // толщина бублика
  const MS_SEC = 1000, MS_MIN = 60000, MS_HOUR = 3600000, MS_DAY = 86400000;

  // Параметры PNG-легенды (повторяют вёрстку карточки)
  const EXP_W = 350;      // ширина изображения
  const EXP_PAD = 16;     // внешний отступ
  const MONO = 'Consolas, "Courier New", monospace';
  const SANS = '"Segoe UI", Roboto, Arial, sans-serif';
  const EMOJI = '"Segoe UI Emoji", "Apple Color Emoji", "Noto Color Emoji"';

  // Луна
  const SYNODIC = 29.530588853;     // средний синодический месяц, сутки
  const NEW_MOON_JD = 2451550.1;    // опорное новолуние: 06.01.2000 18:14 UTC
  const MOON_PHASES = [
    { icon: '🌑', name: 'Новолуние' },
    { icon: '🌒', name: 'Растущий серп' },
    { icon: '🌓', name: 'Первая четверть' },
    { icon: '🌔', name: 'Растущая луна' },
    { icon: '🌕', name: 'Полнолуние' },
    { icon: '🌖', name: 'Убывающая луна' },
    { icon: '🌗', name: 'Последняя четверть' },
    { icon: '🌘', name: 'Убывающий серп' }
  ];

  // Месяцы в родительном падеже (для формата «28 ноября 2026 года»)
  const MONTHS_GEN = [
    'января','февраля','марта','апреля','мая','июня',
    'июля','августа','сентября','октября','ноября','декабря'
  ];

  // ---------- DOM ----------
  const root      = document.documentElement;
  const titleEl   = document.getElementById('title');
  const endInput  = document.getElementById('endInput');
  const canvas    = document.getElementById('donut');
  const ctx       = canvas.getContext('2d');
  const hintEl    = document.getElementById('hint');
  const secEl     = document.getElementById('secondsRemaining');
  const elapsedEl = document.getElementById('elapsed');
  const remEl     = document.getElementById('remaining');
  const remLabel  = document.getElementById('remLabel');
  const infoTable = document.getElementById('infoTable');
  const saveBtn   = document.getElementById('saveBtn');

  // ---------- HiDPI canvas ----------
  const dpr = window.devicePixelRatio || 1;
  canvas.width  = SIZE * dpr;
  canvas.height = SIZE * dpr;

  // ---------- Состояние ----------
  const cssVar = name => getComputedStyle(root).getPropertyValue(name).trim();

  let donutColor = localStorage.getItem(LS_COLOR) || DEFAULT_COLOR;
  let lastHue = parseFloat(localStorage.getItem(LS_HUE));
  if (isNaN(lastHue)) lastHue = -1;
  let appliedAccent = null;

  let endDate = loadEndDate();

  // ---------- Утилиты ----------
  const pad = n => String(n).padStart(2, '0');

  function toInputValue(d){
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}` +
           `T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  }

  // Формат как в поле на экране: 25.03.2027, 00:00:00
  function formatEndDate(d){
    return `${pad(d.getDate())}.${pad(d.getMonth()+1)}.${d.getFullYear()}, ` +
           `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  }

  // Длинный формат даты для заголовка: «28 ноября 2026 года»
  function formatLongDate(d){
    return `${d.getDate()} ${MONTHS_GEN[d.getMonth()]} ${d.getFullYear()} года`;
  }

  // Полное название дня недели с заглавной буквы: «Четверг»
  const WEEKDAYS = ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'];
  function fullWeekDay(d){
    return WEEKDAYS[d.getDay()];
  }

  // Фаза луны на указанный момент
  function getMoonPhase(date){
    const jd  = date.getTime() / MS_DAY + 2440587.5;            // юлианская дата
    const age = (((jd - NEW_MOON_JD) % SYNODIC) + SYNODIC) % SYNODIC; // возраст луны, сутки
    const idx = Math.floor(age / SYNODIC * 8 + 0.5) % 8;
    const illum = Math.round((1 - Math.cos(2 * Math.PI * age / SYNODIC)) / 2 * 100);
    return { ...MOON_PHASES[idx], age, illum };
  }

  function loadEndDate(){
    const saved = localStorage.getItem(LS_END);
    if (saved){
      const d = new Date(saved);
      if (!isNaN(d)) return d;
    }
    return new Date(new Date().getFullYear() + 1, 0, 1, 0, 0, 0); // начало следующего года
  }

  // Склонение: plural(5, ['час','часа','часов'])
  function plural(n, forms){
    n = Math.abs(n) % 100;
    const n1 = n % 10;
    if (n > 10 && n < 20) return forms[2];
    if (n1 > 1 && n1 < 5) return forms[1];
    if (n1 === 1)        return forms[0];
    return forms[2];
  }

  // Разделитель групп разрядов (неразрывный пробел): 31536000 -> «31 536 000»
  function formatInt(n){
    return String(Math.floor(n)).replace(/\B(?=(\d{3})+(?!\d))/g, '\u00A0');
  }

  function formatDuration(ms){
    ms = Math.max(0, Math.floor(ms));
    const d = Math.floor(ms / MS_DAY);
    const h = Math.floor(ms % MS_DAY / MS_HOUR);
    const m = Math.floor(ms % MS_HOUR / MS_MIN);
    const s = Math.floor(ms % MS_MIN  / MS_SEC);
    return `${d} ${plural(d, ['день','дня','дней'])} ` +
           `${h} ${plural(h, ['час','часа','часов'])} ` +
           `${m} ${plural(m, ['минута','минуты','минут'])} ` +
           `${s} ${plural(s, ['секунда','секунды','секунд'])}`;
  }

  // Общее число оставшихся секунд: склонение + согласование глагола + разряды
  function formatSecondsRemaining(c){
    if (c.now > c.end){
      const n = Math.floor((c.now - c.end) / MS_SEC);
      return `Превышено на ${formatInt(n)} ${plural(n, ['секунду','секунды','секунд'])}`;
    }
    const n = Math.max(0, Math.floor(c.remMs / MS_SEC));
    const verb = (n % 10 === 1 && n % 100 !== 11) ? 'Осталась:' : 'Осталось:';
    return `${verb} ${formatInt(n)} ${plural(n, ['секунда','секунды','секунд'])}`;
  }

  // Начало периода = конечная дата минус один календарный год (365/366 дней)
  function getPeriodStart(end){
    const start = new Date(end);
    start.setFullYear(end.getFullYear() - 1);
    if (start.getMonth() !== end.getMonth()) start.setDate(0); // 29 фев -> 28 фев
    return start;
  }

  // Случайный контрастный цвет на тёмном фоне
  function randomColor(){
    let h, tries = 0;
    do {
      h = Math.floor(Math.random() * 360);
      const diff = Math.min(Math.abs(h - lastHue), 360 - Math.abs(h - lastHue));
      const nearRed = h < 15 || h > 345;
      if (!nearRed && (lastHue < 0 || diff >= 50)) break;
    } while (++tries < 100);
    lastHue = h;
    localStorage.setItem(LS_HUE, h);
    const s = 75 + Math.floor(Math.random() * 20);  // 75–94%
    const l = 52 + Math.floor(Math.random() * 12);  // 52–63%
    return `hsl(${h}, ${s}%, ${l}%)`;
  }

  // Любой CSS-цвет -> [r, g, b]
  function toRGB(color){
    const t = document.createElement('canvas');
    t.width = t.height = 1;
    const x = t.getContext('2d');
    x.fillStyle = color;
    x.fillRect(0, 0, 1, 1);
    const d = x.getImageData(0, 0, 1, 1).data;
    return [d[0], d[1], d[2]];
  }

  // Применить акцентный цвет: бублик, кнопка и secondsRemaining используют один цвет
  // (secondsRemaining берёт его из CSS-переменной --primary)
  function applyAccent(color){
    if (color === appliedAccent) return;
    appliedAccent = color;
    const [r, g, b] = toRGB(color);
    const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    root.style.setProperty('--primary', color);
    root.style.setProperty('--on-primary', lum > 0.55 ? '#0f1720' : '#ffffff');
  }

  // ---------- Расчёт ----------
  function calc(){
    const now   = new Date();
    const end   = endDate;
    const start = getPeriodStart(end);
    const total = end - start;                       // 100% (365 или 366 дней)
    const totalDays = Math.round(total / MS_DAY);

    const elapsedMs = Math.max(0, now - start);
    const remMs     = end - now;
    const exceeded  = now > end || now < start;      // вышли за пределы периода

    let remPct, elapsedPct;
    if (now > end){
      remPct = 0;
      elapsedPct = 100;
    } else if (now < start){
      remPct = remMs / total * 100;                  // может быть > 100
      elapsedPct = 0;
    } else {
      remPct = Math.round(remMs / total * 10000) / 100;
      elapsedPct = Math.round((100 - remPct) * 100) / 100; // сумма всегда 100.00
    }
    if (now < start) remPct = Math.round(remPct * 100) / 100;

    return { now, start, end, total, totalDays, elapsedMs, remMs, exceeded, elapsedPct, remPct };
  }

  // Тексты легенды — единый источник для экрана и для PNG
  function getTexts(c){
    const title = formatLongDate(c.end);
    const hint = `100% = ${c.totalDays} ${plural(c.totalDays, ['день','дня','дней'])}` +
                 (c.totalDays === 366 ? ' (високосный период)' : '');
    const elapsed = `${c.elapsedPct.toFixed(2)}% · ${formatDuration(c.elapsedMs)}`;
    let remLbl, rem;
    if (c.now > c.end){
      remLbl = 'Превышено';
      rem = '+ ' + formatDuration(c.now - c.end);
    } else {
      remLbl = 'Осталось:';
      rem = `${c.remPct.toFixed(2)}% · ${formatDuration(c.remMs)}`;
    }
    const seconds = formatSecondsRemaining(c);
    return { title, hint, elapsed, remLbl, rem, seconds };
  }

  // ---------- Отрисовка бублика ----------
  // Рисует в координатах (0..SIZE); трансформ и позицию задаёт вызывающий код
  function drawDonut(target, c){
    const muted = cssVar('--muted');
    const white = cssVar('--white');

    const cx = SIZE / 2, cy = SIZE / 2;
    const r = SIZE / 2 - LINE / 2 - 8;
    const startAng = -Math.PI / 2;

    // дорожка
    target.lineWidth = LINE;
    target.lineCap = 'butt';
    target.strokeStyle = 'rgba(255,255,255,.08)';
    target.beginPath();
    target.arc(cx, cy, r, 0, Math.PI * 2);
    target.stroke();

    // прогресс — обратный: показывает ОСТАВШЕЕСЯ время
    const color = c.exceeded ? RED : donutColor;
    const frac  = c.exceeded ? 1 : Math.min(1, Math.max(0, c.remPct / 100));
    if (frac > 0){
      target.strokeStyle = color;
      target.beginPath();
      target.arc(cx, cy, r, startAng, startAng + Math.PI * 2 * frac);
      target.stroke();
    }

    // текст в центре
    target.textAlign = 'center';
    target.textBaseline = 'middle';

    // День недели выбранной даты (с заглавной буквы)
    target.fillStyle = c.exceeded ? ALERT_TEXT : color;
    target.font = `600 13px ${SANS}`;
    target.fillText(fullWeekDay(c.end), cx, cy - 56);

    target.fillStyle = white;
    target.font = `700 32px ${MONO}`;
    target.fillText(c.remPct.toFixed(2) + '%', cx, cy - 26);

    target.fillStyle = muted;
    target.font = `12px ${SANS}`;
    target.fillText('осталось', cx, cy - 2);

    target.fillStyle = c.exceeded ? ALERT_TEXT : muted;
    target.font = `600 14px ${MONO}`;
    target.fillText('прошло ' + c.elapsedPct.toFixed(2) + '%', cx, cy + 20);

    // Фаза луны на выбранную дату (иконка + название)
    const moon = getMoonPhase(c.end);
    target.fillStyle = muted;
    target.font = `12px ${SANS}, ${EMOJI}`;
    target.fillText(`${moon.icon} ${moon.name}`, cx, cy + 46);
  }

  function drawScreen(c){
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, SIZE, SIZE);
    drawDonut(ctx, c);
  }

  // ---------- Экспорт всей легенды в PNG ----------
  function roundRectPath(t, x, y, w, h, r){
    t.beginPath();
    t.moveTo(x + r, y);
    t.arcTo(x + w, y,     x + w, y + h, r);
    t.arcTo(x + w, y + h, x,     y + h, r);
    t.arcTo(x,     y + h, x,     y,     r);
    t.arcTo(x,     y,     x + w, y,     r);
    t.closePath();
  }

  // Перенос текста по ширине (по обычным пробелам; неразрывные не разрываются)
  function wrapText(t, text, maxW){
    const words = text.split(' ');
    const lines = [];
    let line = '';
    for (const w of words){
      const test = line ? line + ' ' + w : w;
      if (line && t.measureText(test).width > maxW){
        lines.push(line);
        line = w;
      } else {
        line = test;
      }
    }
    if (line) lines.push(line);
    return lines;
  }

  function buildLegendCanvas(c){
    const scale = Math.max(dpr, 2);
    const t = document.createElement('canvas');
    const tx = t.getContext('2d');

    const bg     = cssVar('--bg');
    const muted  = cssVar('--muted');
    const white  = cssVar('--white');
    const mono   = cssVar('--mono');
    const texts  = getTexts(c);

    const CW = EXP_W - EXP_PAD * 2;       // ширина содержимого
    const LABEL_W = 82;                   // ширина колонки подписей
    const CELL_PX = 10;                   // горизонтальный отступ ячейки
    const VAL_W = CW - LABEL_W - CELL_PX; // ширина колонки значений
    const LINE_H = 12.5 * 1.35;
    const ROW_PAD = 7;

    // --- 1) Измеряем таблицу, чтобы узнать высоту ---
    tx.font = `12.5px ${MONO}`;
    const rows = [
      { label: 'Прошло:',     lines: wrapText(tx, texts.elapsed, VAL_W) },
      { label: texts.remLbl, lines: wrapText(tx, texts.rem,     VAL_W) },
    ].map(r => ({ ...r, h: ROW_PAD * 2 + r.lines.length * LINE_H }));
    const tableH = rows.reduce((s, r) => s + r.h, 0);

    // --- 2) Высота всего изображения ---
    const H1_H = 22, LABEL_H = 14, INPUT_H = 34, GAP = 10, HINT_H = 14, SEC_H = 20;
    const H = Math.ceil(
      EXP_PAD +
      H1_H + GAP +
      LABEL_H + 4 + INPUT_H + GAP +
      SIZE + GAP +
      HINT_H + GAP +
      SEC_H + GAP +
      tableH +
      EXP_PAD
    );

    t.width  = EXP_W * scale;
    t.height = H * scale;
    tx.setTransform(scale, 0, 0, scale, 0, 0);

    // --- 3) Фон ---
    tx.fillStyle = bg;
    tx.fillRect(0, 0, EXP_W, H);

    let y = EXP_PAD;
    const x0 = EXP_PAD;

    // --- 3.1) Заголовок h1 (введённая дата) ---
    tx.textAlign = 'center';
    tx.textBaseline = 'middle';
    tx.fillStyle = white;
    tx.font = `700 18px ${SANS}`;
    if ('letterSpacing' in tx) tx.letterSpacing = '0.5px';
    tx.fillText(texts.title, EXP_W / 2, y + H1_H / 2);
    if ('letterSpacing' in tx) tx.letterSpacing = '0px';
    y += H1_H + GAP;

    // --- 4) Подпись и поле конечной даты ---
    tx.textAlign = 'left';
    tx.textBaseline = 'top';
    tx.fillStyle = muted;
    tx.font = `12px ${SANS}`;
    tx.fillText('Конечная дата и время', x0, y);
    y += LABEL_H + 4;

    roundRectPath(tx, x0 + .5, y + .5, CW - 1, INPUT_H - 1, 8);
    tx.fillStyle = 'rgba(255,255,255,0.04)';
    tx.fill();
    tx.lineWidth = 1;
    tx.strokeStyle = 'rgba(255,255,255,0.12)';
    tx.stroke();

    tx.fillStyle = white;
    tx.font = `14px ${SANS}`;
    tx.textBaseline = 'middle';
    tx.fillText(formatEndDate(c.end), x0 + 10, y + INPUT_H / 2 + 1);
    y += INPUT_H + GAP;

    // --- 5) Бублик ---
    tx.save();
    tx.translate(x0 + (CW - SIZE) / 2, y);
    drawDonut(tx, c);
    tx.restore();
    y += SIZE + GAP;

    // --- 6) Подсказка «100% = N дней» ---
    tx.textAlign = 'center';
    tx.textBaseline = 'middle';
    tx.fillStyle = muted;
    tx.font = `11px ${SANS}`;
    tx.fillText(texts.hint, EXP_W / 2, y + HINT_H / 2);
    y += HINT_H + GAP;

    // --- 6.1) Оставшиеся секунды (цвет как у бублика и кнопки) ---
    tx.textAlign = 'center';
    tx.textBaseline = 'middle';
    tx.fillStyle = c.exceeded ? RED : donutColor;
    tx.font = `700 15px ${MONO}`;
    tx.fillText(texts.seconds, EXP_W / 2, y + SEC_H / 2);
    y += SEC_H + GAP;

    // --- 7) Таблица ---
    roundRectPath(tx, x0 + .5, y + .5, CW - 1, tableH - 1, 10);
    tx.fillStyle = 'rgba(255,255,255,0.04)';
    tx.fill();
    tx.strokeStyle = 'rgba(255,255,255,0.08)';
    tx.stroke();

    tx.save();
    roundRectPath(tx, x0, y, CW, tableH, 10);
    tx.clip();

    let ry = y;
    rows.forEach((r, i) => {
      // разделитель между строками
      if (i > 0){
        tx.fillStyle = 'rgba(255,255,255,0.08)';
        tx.fillRect(x0, ry, CW, 1);
      }

      // подпись (верхний регистр, мелкий шрифт)
      tx.textAlign = 'left';
      tx.textBaseline = 'top';
      tx.fillStyle = c.exceeded ? ALERT_TEXT : muted;
      tx.font = `11px ${SANS}`;
      if ('letterSpacing' in tx) tx.letterSpacing = '0.5px';
      tx.fillText(r.label.toUpperCase(), x0 + CELL_PX, ry + ROW_PAD + 2);
      if ('letterSpacing' in tx) tx.letterSpacing = '0px';

      // значение (многострочное)
      tx.fillStyle = c.exceeded ? ALERT_TEXT : mono;
      tx.font = `12.5px ${MONO}`;
      r.lines.forEach((ln, li) => {
        tx.fillText(ln, x0 + LABEL_W, ry + ROW_PAD + li * LINE_H);
      });

      ry += r.h;
    });
    tx.restore();

    return t;
  }

  // ---------- Обновление ----------
  function update(){
    const c = calc();

    // единый цвет для бублика, кнопки и secondsRemaining
    applyAccent(c.exceeded ? RED : donutColor);

    drawScreen(c);

    const texts = getTexts(c);
    titleEl.textContent   = texts.title;
    hintEl.textContent    = texts.hint;
    secEl.textContent     = texts.seconds;
    elapsedEl.textContent = texts.elapsed;
    remLabel.textContent  = texts.remLbl;
    remEl.textContent     = texts.rem;
    infoTable.classList.toggle('alert', c.exceeded);
  }

  // ---------- События ----------
  endInput.value = toInputValue(endDate);
  endInput.addEventListener('change', () => {
    const d = new Date(endInput.value);
    if (isNaN(d)) return;
    endDate = d;
    localStorage.setItem(LS_END, d.toISOString());
    update();
  });

  // Случайный цвет по клику на кольцо — меняет бублик, кнопку и secondsRemaining
  canvas.addEventListener('click', e => {
    const rect = canvas.getBoundingClientRect();
    const x = (e.clientX - rect.left) * (SIZE / rect.width)  - SIZE / 2;
    const y = (e.clientY - rect.top)  * (SIZE / rect.height) - SIZE / 2;
    const dist = Math.hypot(x, y);
    const r = SIZE / 2 - LINE / 2 - 8;
    if (dist < r - LINE / 2 - 4 || dist > r + LINE / 2 + 4) return;

    donutColor = randomColor();
    localStorage.setItem(LS_COLOR, donutColor);
    update();
  });

  // Сохранение всей легенды (h1 + поле даты + бублик + подсказка + секунды + таблица) в PNG
  saveBtn.addEventListener('click', () => {
    const off = buildLegendCanvas(calc());
    off.toBlob(blob => {
      if (!blob) return;
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = Date.now() + '.png';
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }, 'image/png');
  });

  update();
  setInterval(update, 1000);
})();
</script>
</body>
</html>
Editor is loading...
Leave a Comment