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

查看:115
本文介绍了使用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 dataset属性,一个用于保存当前颜色点的数组。单击某个点时,关联的数组值将更改为 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天全站免登陆