【问题标题】:Change style of hover and tooltip in chartjs or ng2-charts在 chartjs 或 ng2-charts 中更改悬停和工具提示的样式
【发布时间】:2019-09-08 15:17:29
【问题描述】:

有什么方法可以改变悬停样式以及使用 chartjs 或 ng2-charts 的工具提示?我想隐藏悬停点,并且只在我将鼠标悬停在它们上时才显示它们,并将指示器作为线。这是我要构建的确切图表模型:

https://interactive-bitcoin-price-chart-foxkmkynmg.now.sh/

提前感谢您的提示。

编辑:我按照 GRUNT 的说明将此图表选项应用到我的 Angular 应用程序中,每当我悬停时,都会显示完整的图表和工具提示,但线跟踪指示器不是。这是我的代码:

插件-hoverline.ts:

export class PluginHoverline {
   posX: null;
   isMouseOut:boolean = false;

   drawLine(chart, posX) {
      const ctx = chart.ctx,
         x_axis = chart.scales['x-axis-0'],
         y_axis = chart.scales['y-axis-0'],
         x = posX,
         topY = y_axis.top,
         bottomY = y_axis.bottom;
      if (posX < x_axis.left || posX > x_axis.right) return;
      // draw line
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(x, topY);
      ctx.lineTo(x, bottomY);
      ctx.lineWidth = chart.options.lineOnHover.lineWidth;
      ctx.strokeStyle = chart.options.lineOnHover.lineColor;
      ctx.stroke();
      ctx.restore();
   };

   beforeInit(chart) {
      chart.options.events.push('mouseover');
   };

   afterEvent(chart, event) {
      if (!chart.options.lineOnHover || !chart.options.lineOnHover.enabled) return;
      if (event.type !== 'mousemove' && event.type !== 'mouseover') {
         if (event.type === 'mouseout') this.isMouseOut = true;
         chart.clear();
         chart.draw();
         return;
      }
      this.posX = event.x;
      this.isMouseOut = false;
      chart.clear();
      chart.draw();
      this.drawLine(chart, this.posX);

      var metaData = chart.getDatasetMeta(0).data,
         radius = chart.data.datasets[0].pointHoverRadius,
         posX = metaData.map(e => e._model.x);
      posX.forEach(function(pos, posIndex) {
         if (this.posX < pos + radius && this.posX > pos - radius) {
            chart.updateHoverStyle([metaData[posIndex]], null, true);
            chart.tooltip._active = [metaData[posIndex]];
         } else chart.updateHoverStyle([metaData[posIndex]], null, false);
      }.bind(this));
      chart.tooltip.update();
   };

   afterDatasetsDraw(chart, ease) {
      if (!this.posX) return;
      if (!this.isMouseOut) this.drawLine(chart, this.posX);
   };
}

banner.component.ts:(图表组件)

import { Component, OnInit } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import { PluginHoverline } from './plugin-hoverline';

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

  private dataUrl: string = 'historical/close.json';

  constructor(
    private historicalBpiService:HistoricalBpiService
  ) {}

  // lineChart
  public lineChartData:any = [
    { data:[], label: 'Bitcoin price' }
  ];

  public lineChartLabels:Array<any> = [];

  public lineChartOptions:any = {
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: 0
    },
    lineOnHover: {
     enabled: true,
     lineColor: '#bbb',
     lineWidth: 1
   },
    scales: {
      yAxes: [{
        display: true,
        scaleLabel: {
          display: false,
          labelString: 'USD'
        },
        ticks: {
          display: false
        },
        gridLines: {
          display: true,
          tickMarkLength: 0
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          display: false,
          tickMarkLength: 0
        }
      }]
    },
    elements: {
      point: {
        radius: 3
      },
      line: {
        tension: 0.4, // 0 disables bezier curves
      }
    },
    hover: {
      mode: 'nearest',
      intersect: false
    },
    tooltips: {
      mode: 'nearest',
      intersect: false,
      backgroundColor: 'rgb(95,22,21)',
      callbacks: {
        label: function (tooltipItems, data) {
          return data.datasets[tooltipItems.datasetIndex].label + ' : ' + '$' + tooltipItems.yLabel.toLocaleString();
        },
        labelColor: function(tooltipItem, chart) {
          var dataset = chart.config.data.datasets[tooltipItem.datasetIndex];
          return {
            backgroundColor : dataset.backgroundColor
          }
        }
      }
    }
  };
  public lineChartColors:Array<any> = [
    {
      backgroundColor: 'rgba(199,32,48,0.8',
      borderColor: 'rgb(95,22,21);',
      pointBackgroundColor: 'rgba(218,208,163,0.8)',
      pointHoverBackgroundColor: 'rgba(218,208,163,0.8)',
      pointHoverBorderColor: 'rgb(218,208,163)',
      pointHoverRadius: 6,
      steppedLine: false

    }
  ];
  public lineChartLegend:boolean = false;
  public lineChartType:string = 'line';


  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

  ngOnInit(){
    this.historicalBpiService.getBpiData(this.dataUrl)
      .subscribe(
        res => {
          //this.lineChartData = Object.keys(res.bpi).map(function (key) { return res.bpi[key];});
          this.lineChartData[0].data = Object.values(res.bpi);
          this.lineChartLabels = Object.keys(res.bpi);
          //console.log(this.lineChartData,this.lineChartLabels);
        }
      )
  }
}

模板:

<div class="chart">
      <canvas baseChart height="360px"
        [datasets]="lineChartData"
        [labels]="lineChartLabels"
        [options]="lineChartOptions"
        [colors]="lineChartColors"
        [legend]="lineChartLegend"
        [chartType]="lineChartType"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)"></canvas>
    </div>

【问题讨论】:

    标签: chart.js ng2-charts


    【解决方案1】:

    不幸的是,目前还没有内置功能。但是您可以使用this 图表插件(曾经为我自己的目的创建) 来实现您的目标。

    要使用该插件,请在图表的选项配置中设置以下选项:

    lineOnHover: {
       enabled: true,
       lineColor: '#bbb',
       lineWidth: 1
    }
    

    另外,请确保为您的数据集设置以下属性:

    pointRadius: 0,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: 'white'
    

    见 - live demo

    【讨论】:

    • 好的,谢谢你的信息。现在这个带有插件的解决方案很好。您有其他不使用外部插件的解决方案吗?我在 npm 上搜索过类似的插件,但没有找到。
    • 不!正如我所说,这个atm没有本机解决方案。您必须使用插件,并且使用插件没有害处,因为它们用于扩展图表功能,如果您需要任何自定义功能,您甚至可以创建自己的插件。话虽这么说,这是一个定制的插件,在 npm 上找不到(因为我还没有发布它)
    • 嗨,但是如何注册这个插件并在我的 Angular cli 应用程序的图表组件中使用它?
    • 首先,在本地下载插件脚本并将其文件扩展名为.ts。然后将其放在您的图表组件文件夹中,然后将其 (import './chartjs-plugin-hoverline';) 导入您的 chart.component.ts 文件中。
    • 您好,我编辑了我的问题,包括我的代码。你能看看吗?谢谢
    【解决方案2】:

    这个答案是建立在GRUNT's answer above 之上的,以便能够显示它是否是多线图:


    只需更改以下内容(在他提供的代码 sn-p 中here):

    posX.forEach(function(pos, posIndex) {
      if (this.posX < pos + radius && this.posX > pos - radius) {
        chart.updateHoverStyle([metaData[posIndex]], null, true);
        chart.tooltip._active = [metaData[posIndex]];
      } else chart.updateHoverStyle([metaData[posIndex]], null, false);
    }.bind(this));
    

    到:

    posX.forEach(function(pos, posIndex) {
      var metaDatum = []
      if (this.posX < pos + radius && this.posX > pos - radius) {
        chart.data.datasets.forEach((dataset, ind) => {
          metaDatum.push(chart.getDatasetMeta(ind).data[posIndex]);
        })
    
        chart.updateHoverStyle(metaDatum, null, true);
        chart.tooltip._active = metaDatum;
      } else {
        metaDatum.push(metaData[posIndex]);
        chart.updateHoverStyle(metaDatum, null, false);
      }
    }.bind(this));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-24
      • 2019-04-03
      • 2019-12-01
      • 2021-12-30
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多