Вертикальная линия на нескольких графиках - PullRequest
0 голосов
/ 09 июля 2020

Я пытаюсь нанести вертикальную линию на все диаграммы с одинаковой маркировкой. Решение, которое я нашел и модифицировал, хорошо работает только на активном графике - там корректно отображается строка с подсказкой. На других диаграммах линия находится там, где она должна быть, но при перемещении в другое положение по оси x она не удаляется и постепенно покрывает всю диаграмму.

Я как-то решил эту проблему, отправив событие наведения курсора мыши для всех диаграмм, но он слишком медленный и не соответствует моим ожиданиям.

Я просто хочу удалить тени от линий из неактивных диаграмм.

Вот мой пример кода:

 var charts = [];

    $(document).ready(function () {

        Chart.defaults.LineWithLine = Chart.defaults.line;
        Chart.controllers.LineWithLine = Chart.controllers.line.extend({
            draw: function(ease) {
                Chart.controllers.line.prototype.draw.call(this, ease);

                if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
                    charts.forEach(chart => {
                    var activePoint = this.chart.tooltip._active[0],
                        ctx = chart.ctx,
                        x = activePoint.tooltipPosition().x,
                        topY = this.chart.scales['y-axis-0'].top,
                        bottomY = this.chart.scales['y-axis-0'].bottom;

                    // draw line
                    ctx.save();
                    ctx.beginPath();
                    ctx.moveTo(x, topY);
                    ctx.lineTo(x, bottomY);
                    ctx.lineWidth = 2;
                    ctx.strokeStyle = '#07C';
                    ctx.stroke();
                    ctx.restore();
                  })
                }
            }
        });



        var ctx1 = document.getElementById('myChart1').getContext('2d');
        var chart1 = new Chart(ctx1, {
            type: 'LineWithLine',
            data: {
                labels: ['Segment 1', 'Segment 2', 'Segment 3','Segment 4','Segment 5','Segment 6','Segment 7','Segment 8','Segment 9','Segment 10','Segment 11','Segment 12'],
                datasets: [{
                    lineTension: 0,
                    backgroundColor: "rgb(34,139,34)",
                    borderColor: "rgb(34,139,34)",
                    data: [14, 19, 20, 10, 6, 15, 8, 27, 25, 14, 36, 22],
                    fill: false,
                    pointRadius: 1.5,
                    pointHoverRadius: 1,
                    borderWidth :1.5
                }],
                fill: false,
                pointRadius: 0,
                borderWidth: 1,
            },
            options: {
                maintainAspectRatio: false,
                hover: {
                    mode: 'index',
                    intersect: false,
                },
                title: {
                    display: true,
                    text: ''
                },
                legend: {
                    display: false
                },
                tooltips: {
                    mode: 'index',
                    //enabled: false,
                    intersect: false,
                },
            }
        });
        
        
        var ctx2 = document.getElementById('myChart2').getContext('2d');
        var chart = new Chart(ctx2, {
            type: 'LineWithLine',
            data: {
                labels: ['Segment 1', 'Segment 2', 'Segment 3','Segment 4','Segment 5','Segment 6','Segment 7','Segment 8','Segment 9','Segment 10','Segment 11','Segment 12'],
                datasets: [{
                    lineTension: 0,
                    backgroundColor: "rgb(34,139,34)",
                    borderColor: "rgb(34,139,34)",
                    data: [14, 11, 10, 20, 20, 15, 25, 15, 13, 14, 16, 8],
                    fill: false,
                    pointRadius: 1.5,
                    pointHoverRadius: 1,
                    borderWidth :1.5
                }],
            },
            options: {
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: ''
                },
                legend: {
                    display: false
                },
                tooltips: {
                    mode: 'index',
                    intersect: false,
                },
            }

        });

        charts.push(chart)
        charts.push(chart1)

    });
<h3 style="text-align: center">Hi ChartJs!</h3>
<div>
    <canvas style="width: 500px" height="200px" id="myChart1"></canvas>
</div>
<div>
    <canvas style="width: 500px" height="200px" id="myChart2"></canvas>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>

1 Ответ

0 голосов
/ 12 июля 2020

Внутри вашей функции draw() вам нужно вызвать draw() на другом графике. Чтобы избежать появления устаревших всплывающих подсказок на диаграмме, которые теряют фокус, вы также должны убедиться, что для его параметра tooltips.enabled установлено значение false.

charts.forEach(chart => {         
  chart.options.tooltips.enabled = this.chart == chart;
  if (this.chart != chart) {
    chart.draw();
  }

Обратите внимание на измененный код ниже.

var charts = [];

$(document).ready(function() {
  Chart.defaults.LineWithLine = Chart.defaults.line;
  Chart.controllers.LineWithLine = Chart.controllers.line.extend({
    draw: function(ease) {
      Chart.controllers.line.prototype.draw.call(this, ease);
      if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
        charts.forEach(chart => {         
          chart.options.tooltips.enabled = this.chart == chart;
          if (this.chart != chart) {
            chart.draw();
          }
          var activePoint = this.chart.tooltip._active[0];
          var ctx = chart.ctx;
          var x = activePoint.tooltipPosition().x;
          var topY = this.chart.scales['y-axis-0'].top;
          var bottomY = this.chart.scales['y-axis-0'].bottom;
          // draw line
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(x, topY);
          ctx.lineTo(x, bottomY);
          ctx.lineWidth = 2;
          ctx.strokeStyle = '#07C';
          ctx.stroke();
          ctx.restore();
        })
      }
    }
  });

  var ctx1 = document.getElementById('myChart1').getContext('2d');
  var chart1 = new Chart(ctx1, {
    type: 'LineWithLine',
    data: {
      labels: ['Segment 1', 'Segment 2', 'Segment 3', 'Segment 4', 'Segment 5', 'Segment 6', 'Segment 7', 'Segment 8', 'Segment 9', 'Segment 10', 'Segment 11', 'Segment 12'],
      datasets: [{
        lineTension: 0,
        backgroundColor: "rgb(34,139,34)",
        borderColor: "rgb(34,139,34)",
        data: [14, 19, 20, 10, 6, 15, 8, 27, 25, 14, 36, 22],
        fill: false,
        pointRadius: 1.5,
        pointHoverRadius: 1,
        borderWidth: 1.5
      }],
      fill: false,
      pointRadius: 0,
      borderWidth: 1,
    },
    options: {
      maintainAspectRatio: false,
      hover: {
        mode: 'index',
        intersect: false,
      },
      title: {
        display: true,
        text: ''
      },
      legend: {
        display: false
      },
      tooltips: {
        mode: 'index',
        //enabled: false,
        intersect: false,
      },
    }
  });

  var ctx2 = document.getElementById('myChart2').getContext('2d');
  var chart = new Chart(ctx2, {
    type: 'LineWithLine',
    data: {
      labels: ['Segment 1', 'Segment 2', 'Segment 3', 'Segment 4', 'Segment 5', 'Segment 6', 'Segment 7', 'Segment 8', 'Segment 9', 'Segment 10', 'Segment 11', 'Segment 12'],
      datasets: [{
        lineTension: 0,
        backgroundColor: "rgb(34,139,34)",
        borderColor: "rgb(34,139,34)",
        data: [14, 11, 10, 20, 20, 15, 25, 15, 13, 14, 16, 8],
        fill: false,
        pointRadius: 1.5,
        pointHoverRadius: 1,
        borderWidth: 1.5
      }],
    },
    options: {
      maintainAspectRatio: false,
      title: {
        display: true,
        text: ''
      },
      legend: {
        display: false
      },
      tooltips: {
        mode: 'index',
        intersect: false,
      },
    }

  });
  charts.push(chart)
  charts.push(chart1)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>

<div>
  <canvas style="width: 500px" height="200px" id="myChart1"></canvas>
</div>
<div>
  <canvas style="width: 500px" height="200px" id="myChart2"></canvas>
</div>
...