chartjs在onHover上显示十字准线

时间:2019-10-23 08:45:12

标签: chart.js

https://codepen.io/qkreltms/pen/BaaWZeV?editors=0010

将鼠标悬停在点上时,我尝试过十字准线: enter image description here

但是有一些错误

  1. 当鼠标悬停在点上几乎正好位于点上而不是任何位置上时,就会出现十字线。
  2. 当鼠标点移到该点上时,十字线边框变粗。

有什么想法吗?

代码:

var ctx = document.getElementById("myChart").getContext("2d");

const colors = {
  darkBlue: {
    fill: '#92bed2',
    stroke: '#3282bf',
  },
  purple: {
    fill: '#8fa8c8',
    stroke: '#75539e',
  }
};

const test = [5, 9, 10, 9, 18, 19, 20];


const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: test,
    datasets: [{
      label: "Unavailable",
      fill: true,
      backgroundColor: colors.purple.fill,
      pointBackgroundColor: colors.purple.stroke,
      borderColor: colors.purple.stroke,
      pointHighlightStroke: colors.purple.stroke,
      borderCapStyle: 'butt',
      data: test,
    }]
  },
  options: {
    onHover: function(event) {
      const chart = myChart.getElementAtEvent(event)[0]._chart;
      const activeElements = myChart.getElementsAtEvent(event);
      console.log(chart)
      if (activeElements.length) {
        const activePoint = activeElements[0];
        const ctx = chart.ctx;
        if (!ctx) {
          return;
        }
        const x = activePoint._view.x;
        const y = activePoint._view.y;
        const leftX = chart.chartArea.left;
        const topY = chart.chartArea.top;
        const RightX = chart.chartArea.right;
        const bottomY = chart.chartArea.bottom;
        ctx.beginPath();
        // ctx.setLineDash([5, 15]);
        ctx.moveTo(x, topY);
        ctx.lineTo(x, bottomY);
        ctx.moveTo(leftX, y);
        ctx.lineTo(RightX, y);
        ctx.lineWidth = 1;
        ctx.strokeStyle = "#C2C7CC";
        ctx.stroke();
        ctx.closePath();
      }
    },
    responsive: false,
    scales: {
    },
    animation: {
      duration: 750,
    },
  }
});

0 个答案:

没有答案