Диаграмма. js Настройка подсказок - PullRequest
0 голосов
/ 08 января 2020

Попытайтесь выяснить, как хранить настроенный информационный текст для всплывающей подсказки каждой панели. (см. изображение ниже)?

Нажмите здесь, чтобы увидеть изображение

Процент исчисляется из расчета прайс-листа и цены продажи, и текст будет изменение на основе положительного и отрицательного процента.

Вот код. Текст подсказки в настоящее время жестко закодирован.

  Chart.defaults.global.defaultFontSize = 10;

var listPriceData = {
  label: 'Average list price',
  data: [100, 200, 300, 400, 500, 600],
  backgroundColor: '#ff937f',
  borderWidth: 0,
  yAxisID: "y-axis-0"
};

var salePriceData = {
  label: 'Average sale price',
  data: [150, 250, 350, 450, 550, 650],
  backgroundColor: '#fed6ce',
  borderWidth: 0,
  yAxisID: "y-axis-0"
};

var allData = {
  labels: ["8/2019", "9/2019", "10/2019", "11/2019", "12/2019", "1/2020"],
  datasets: [listPriceData, salePriceData]
};

var chartOptions = {
  legend: {
    display: false
  },
  hover: {
    animationDuration: 0
  },
  animation: {
    duration: 1,
    onComplete: function (el) {
      var chartInstance = this.chart,
          ctx = chartInstance.ctx;
      ctx.font = Chart.helpers.fontString(
                  Chart.defaults.global.defaultFontSize = 12,
                  Chart.defaults.global.defaultFontStyle = "bold",
                  Chart.defaults.global.defaultFontFamily
                );
      ctx.fillStyle = el.chart.config.options.defaultFontColor;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';

      this.data.datasets.forEach(function (dataset, i) {
        var meta = chartInstance.controller.getDatasetMeta(i);
        meta.data.forEach(function (bar, index) {
          var data = dataset.data[index];
          ctx.fillText(data, bar._model.x, bar._model.y - 5);
        });
      });
    }
  },
  tooltips: {
      enabled: false,
      custom: function(tooltipModel) {
          // Tooltip Element
          var tooltipEl = document.getElementById('home-appreciation-tooltip');

          // Create element on first render
          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'home-appreciation-tooltip';
              tooltipEl.innerHTML = '<table></table>';
              document.body.appendChild(tooltipEl);
          }

          // Hide if no tooltip
          if (tooltipModel.opacity === 0) {
              tooltipEl.style.opacity = 0;
              return;
          }

          // Set caret Position
          tooltipEl.classList.remove('above', 'below', 'no-transform');
          if (tooltipModel.yAlign) {
              tooltipEl.classList.add(tooltipModel.yAlign);
          } else {
              tooltipEl.classList.add('no-transform');
          }

          function getBody(bodyItem) {
              return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {
              var titleLines = tooltipModel.title || [];
              var bodyLines = tooltipModel.body.map(getBody);

              var innerHtml = '<thead>';

              titleLines.forEach(function(title) {
                  innerHtml += '<tr><th>' + "<h5>+0.2%</h5>" + '</th></tr>';
              });
              innerHtml += '</thead><tbody>';

              bodyLines.forEach(function(body, i) {
                  var colors = tooltipModel.labelColors[i];
                  // innerHtml += '<tr><td>' + body + '</td></tr>';
                  innerHtml += '<tr><td>' + "Homes are selling for 110% of list price" + '</td></tr>';
              });
              innerHtml += '</tbody>';

              var tableRoot = tooltipEl.querySelector('table');
              tableRoot.innerHTML = innerHtml;
          }

          // `this` will be the overall tooltip
          var position = this._chart.canvas.getBoundingClientRect();

          // Display, position, and set styles for font
          tooltipEl.style.opacity = 1;
          tooltipEl.style.position = 'absolute';
          tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX - 65 + 'px';
          tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY - 85 + 'px';
          tooltipEl.style.pointerEvents = 'none';
      }
  },
  scales: {
    xAxes: [{
      barPercentage: 1,
      categoryPercentage: 0.6,
      ticks: {
        fontColor: "#8292A2",
        fontSize: 10,
      },
      gridLines: {
        display: false,
        color: "rgb(226, 230, 233)",
        offsetGridLines: true
      }
    }],

    yAxes: [
      {
        display: false,
      },
      {
        type: "linear",
        id: "y-axis-0",
        display: true,
        ticks: {
          fontColor: "#202C4A",
          fontSize: 10,
          fontStyle: "bold",
          beginAtZero: true,
          callback: function(value, index, values) {
            return "$" + value + "k";
          }
        },
        gridLines: {
          display: true,
          borderDash: [4, 2],
          color: "rgb(226, 230, 233)"
        }
      }]
  }
};

Chart.defaults.global.defaultFontColor = '#263151';

var myCanvas = document.getElementById("homeAppreciationChartCanvas").getContext('2d');

var barChart = new Chart(myCanvas, {
  type: 'bar',
  data: allData,
  options: chartOptions
});
canvas {
  margin-top: 100px;
  max-width: 700px;
}



#home-appreciation-tooltip {
  background-color: #1d2c49;
  border-radius: 3px;
  max-width: 130px;
  width: 130px;
  padding: 5px;
}


#home-appreciation-tooltip:before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  left: 50%;
  transform: translateX(-50%);
  top: 100%;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #1d2c49;
}



#home-appreciation-tooltip table {
  border-collapse: collapse;
}

#home-appreciation-tooltip h5 {
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
  padding: 0 0 3px 0;
  line-height: 1em;
}

#home-appreciation-tooltip p,
#home-appreciation-tooltip td {
  color: #ed6c54;
  font-size: 10px;
  font-weight: bold;
  padding: 0;
  margin: 0;
  line-height: 1em;
}

#home-appreciation-tooltip td,
#home-appreciation-tooltip th {
  text-align: left;
  padding: 0;
  line-height: 1em;
  padding-left: 8px;
  padding-right: 8px;
}

#home-appreciation-tooltip td {
  padding-bottom: 5px;
}

#home-appreciation-tooltip th {
  padding-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

    <canvas id="homeAppreciationChartCanvas"></canvas>
...