使用 ChartJS 单击更改点颜色 [英] Change point color on click using ChartJS

查看:8
本文介绍了使用 ChartJS 单击更改点颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,当您单击单个点(折线图上)时,我可以更改它的颜色,但它会立即变回以前的颜色,我该如何防止这种情况发生?

Currently I'm able to change the color of an individual point (on a line chart) when you click on it but it changes back immediately to previous color, how can I prevent this?

这是我的功能:

var options = {
  onClick: function(e){
    var element = this.getElementAtEvent(e);
    if (element.length > 0) {
      element[0]._view.backgroundColor = '#FFF';
      this.update();
    }
}

我在这里发现了同样的问题 https://github.com/chartjs/Chart.js/issues/2989 显然这家伙能够管理它,但我认为该代码不再兼容.

I found this same issue here https://github.com/chartjs/Chart.js/issues/2989 and apparently the guy was able to manage it but I think that code is no longer compatible.

我正在使用 ChartJS v2.5.0.

I'm using ChartJS v2.5.0.

推荐答案

以下方法利用:

  • pointBackgroundColor 数据集属性,一个保存当前点颜色的数组.单击某个点时,关联的数组值将更改为 white 并更新图表.
  • onClick 图表选项,一个如果事件是'mouseup' 或'click' 类型时调用的函数".它在图表的上下文中调用并传递事件和一组活动元素."
  • the pointBackgroundColor dataset property, an array which will hold the current colors of points. When a point is clicked, the associated array value will be changed to white and the chart will be updated.
  • the onClick chart option, a function that is "called if the event is of type 'mouseup' or 'click'." It is "called in the context of the chart and passed the event and an array of active elements."

更多信息请参见 docs.

长篇大论代码:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [72, 49, 43, 49, 35, 82],
      pointBackgroundColor: ["red", "blue", "yellow", "green", "purple", "orange"]
    }]
  },
  options: {
    onClick: function(evt, activeElements) {
      var elementIndex = activeElements[0]._index;
      this.data.datasets[0].pointBackgroundColor[elementIndex] = 'white';
      this.update();
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

还有一个可以玩的小提琴.

这篇关于使用 ChartJS 单击更改点颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆