chartjs显示悬停在折线图上的点

chartjs show dot point on hover over line chart

本文关键字:折线图 显示 悬停 chartjs      更新时间:2023-09-26

我使用的是Chartjs v.1.0.2,并试图设置一个仅在悬停在图表上时出现的点。之后应该将其移除。我已经设法通过改变对象值来显示它,但它不是流体运动,也不总是显示点。这也不会在悬停时隐藏它。鼠标未结束时,它怎么可能是流动的并隐藏起来?

window.onload = function(){
        var ctx = $("#chart1").get(0).getContext("2d");
                var chart1 = new Chart(ctx).Line(data1, options);

                $("#chart1").hover(function(e) {
                    var activeBars = chart1.getPointsAtEvent(e); 
                    activeBars[0].display = true;
//                    console.log(activeBars[0]);
                    chart1.update();
                 });
    };
    var data1 = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fillColor: "rgba(95,186,88,0.7)",
                    strokeColor: "rgba(95,186,88,1)",
                    pointColor: "rgba(95,186,88,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [65, 59, 80, 81, 56, 55, 40]
                }
            ]
    };

var options = {
    responsive: true,
    bezierCurve : false,
    scaleShowLabels: false,
    scaleFontSize: 0,
    pointDot : false,
    scaleBeginAtZero: true,
    scaleShowHorizontalLines: false,
    scaleShowVerticalLines: true,
    scaleGridLineColor : "rgba(232,232,232)",
    showTooltips: true,
    customTooltips: function (tooltip) {
        var tooltipEl = $('#chartjs-tooltip');
        if (!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }
        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);
        // split out the label and value and make your own tooltip here
        var parts = tooltip.text.split(":");
        var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
        tooltipEl.html(innerHtml);
        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }
};

简化小提琴

使用Chart.js v2.6.0 进行测试

全局设置将起作用:

Chart.defaults.global.hover.intersect = false;

或者直接在图表配置中:

options: {
  hover: {
    intersect: false;
  }
}

以及数据集的点设置。

  • 点的初始颜色应该是透明的
  • 悬停颜色必须设置为所需的颜色

例如

datasets: [{
  label: 'My First dataset',
  borderColor: 'rgb(255, 99, 132)',
  backgroundColor: 'rgb(255, 99, 132)',
  data: [10, 30, 46, 2, 8, 50, 0],
  fill: false,
  pointBorderColor: 'rgba(0, 0, 0, 0)',
  pointBackgroundColor: 'rgba(0, 0, 0, 0)',
  pointHoverBackgroundColor: 'rgb(255, 99, 132)',
  pointHoverBorderColor: 'rgb(255, 99, 132)'}],...

window.onload = function() {
  const mode = 'index';
  const intersect = false;
  const config = {
    type: 'line',
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [{
        label: 'My First dataset',
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgb(255, 99, 132)',
        data: [10, 30, 46, 2, 8, 50, 0],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(255, 99, 132)',
        pointHoverBorderColor: 'rgb(255, 99, 132)',
      }, {
        label: 'My Second dataset',
        borderColor: 'rgb(54, 162, 235)',
        backgroundColor: 'rgb(54, 162, 235)',
        data: [7, 49, 46, 13, 25, 30, 22],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(54, 162, 235)',
        pointHoverBorderColor: 'rgb(54, 162, 235)',
      }]
    },
    options: {
      responsive: true,
      title: {
        display: true,
        text: 'Mode: index, intersect = false'
      },
      tooltips: {
        mode: 'index',
        intersect: intersect,
      },
      hover: {
        mode: mode,
        intersect: intersect
      },
    }
  };
  const ctx = document.getElementById('canvas').getContext('2d');
  const chart = new Chart(ctx, config);
}
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>

Edit:以下解决方案适用于Chart.js v1.0.2(提出此解决方案时的最新版本)。请参阅这个答案,它为Chart.js v2.x.x.提供了一个解决方案


不久前,我遇到了类似的情况,并通过将默认点设置为"0"来解决这个问题;不可见的";如下所示:

  • pointDotRadius设置为1
  • pointStrokeColor设置为白色,alpha设置为0

上面的两个步骤使默认点非常小,这与透明点笔划相结合,使默认点不可见。现在,如果我们使pointDotStrokeWidth足够大,我们就可以实现所需的悬停效果。即

  • pointDotStrokeWidth设置为更大的值(我使用了8)
  • 设置pointColorpointHighlightFillpointHighlightStroke的所需值

[注意:制作pointColor也可以达到同样的效果透明,但如果要绘制多个数据集,则工具提示不会在数据旁边显示相应的线条颜色值。]

下面的例子(或者你可以签出这个Fiddle:ChartJS-在悬停上显示点数):

var data = {
  labels: ["Point0", "Point1", "Point2", "Point3", "Point4"],
  datasets: [
    {
      label: "My Chart",
      fillColor: "rgba(87, 167, 134, 0.2)",
      strokeColor: "rgba(87, 167, 134, 1)",
      pointColor: "rgba(87, 167, 134, 1)",
      pointStrokeColor: "rgba(255, 255, 255, 0)",
      pointHighlightFill: "rgba(87, 167, 134, 0.7)",
      pointHighlightStroke: "rgba(87, 167, 134, 1)",
      data: [5, 39, 109, 19, 149]
    }
  ]
};
var ctx = document.getElementById("my_chart").getContext("2d");
myChart = new Chart(ctx).Line(data, {
  responsive : true,
  bezierCurve: false,
  datasetFill: true,
  pointDotRadius: 1,
  pointDotStrokeWidth: 8,
  pointHitDetectionRadius: 20,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="my_chart"></canvas>

$("#chart1").mouseover(function(e) {
    chart1.datasets[0].points[0].display = true;
    chart1.update();
 });
$("#chart1").mouseout(function(e) {
    chart1.datasets[0].points[0].display = false;
    chart1.update();
 });

尝试使用mouseovermouseout,如下所示。类似地,您也可以使用mouseentermouseleave方法来处理事件。

$("#chart1").mouseover(function(e) {
                var activeBars = chart1.getPointsAtEvent(e); 
                activeBars[0].display = true;
                chart1.update();
             });
$("#chart1").mouseout(function(e) {
                var activeBars = chart1.getPointsAtEvent(e); 
                activeBars[0].display = false;
                chart1.update();
             });

这是一个六年前的问题,但我认为在2022年我们可以使用ChartJS 4.0.1版本。

ChartJS支持交互行为,可以通过图表配置上的interactionhovertooltips设置进行配置。

为此,我们将使用hover设置并选择index模式。此模式在同一索引中查找项目。如果intersect设置为false,则使用x方向上最近的项目来确定索引。

以下是的工作片段

const data = {
  labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
  datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    },
    {
      label: '# of Points',
      data: [7, 11, 5, 8, 3, 7],
      borderWidth: 1
    }
  ]
}
const options = {
  maintainAspectRatio: false,
  elements: {
    point: {
      hoverRadius: 6,
    },
  },
  hover: {
    mode: 'index',
    intersect: false,
  },
}
  
const config = {
  type: 'line',
  data,
  options,
}
const $chart = document.getElementById('chart')
const chart = new Chart($chart, config)
<div class="wrapper" style="width: 98vw; height: 180px">
  <canvas id="chart"></canvas>
</div>
<script src="https://unpkg.com/chart.js@4.0.1/dist/chart.umd.js"></script>