ChartJS 正在尝试更改图表js筛选器中的背景颜色

yhxst69z  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(229)

我是一个新的开发和尝试做一个项目,我创建了一个网页,其中有价格范围过滤器,并有一个图表链接到该价格范围过滤器。我正在尝试做的是改变我的chartJ标签的背景颜色根据游侠过滤器。我希望只有在给定范围内的标签显示橙色,其他标签应显示浅粉红色,但在这里,当我改变背景颜色后,给了一个条件,所有标签的颜色得到改变,但我希望只有标签落在过滤器范围内改变颜色。
trying to achieve range filter in this

  1. let canvasElement = document.getElementById("productChart");
  2. const dataPoints = [21, 0, 19, 3, 5, 0, 2, 3, 10, 4, 6, 7, 2, 0, 0, 0, 24, 30, 32, 45, 44, 22,
  3. 21, 10, 7, 5, 4, 3, 1, 0, 0];
  4. const labels = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  5. 27, 28, 29, 30, 31]
  6. const backgroundColor = 'rgba(255, 99, 71, 0.3)';
  7. const newBackgroundColor = 'rgba(255, 99, 71, 1)';
  8. let config =
  9. {
  10. type: 'bar',
  11. data: {
  12. labels: labels,
  13. datasets: [{
  14. barPercentage: 0.5,
  15. barThickness: 5,
  16. maxBarThickness: 12,
  17. minBarLength: 2,
  18. // label: 'Number of Phones',
  19. data: dataPoints, //price
  20. backgroundColor: backgroundColor,
  21. borderColor: [
  22. 'rgba(255, 99, 71, 0.2)',
  23. ],
  24. borderWidth: 1,
  25. borderRadius: 5,
  26. // borderSkipped: false,
  27. }]
  28. },
  29. options: {
  30. responsive: true,
  31. scales: {
  32. x: {
  33. ticks: {
  34. display: false, //this will remove only the label
  35. },
  36. grid: {
  37. display:false,
  38. borderColor: 'black', // <-- this line is answer to initial question
  39. borderWidth:2,
  40. }
  41. },
  42. y: {
  43. display: false, //this will remove only the label
  44. },
  45. },
  46. plugins: {
  47. legend: {
  48. display: false,
  49. },
  50. tooltip: {
  51. enabled: false,
  52. displayColors: false,
  53. padding: 10,
  54. yAlign: 'top',
  55. },
  56. },
  57. }
  58. }
  59. let productChart = new Chart(canvasElement, config)
  60. const start = document.getElementById('start')
  61. const end = document.getElementById('end')
  62. function updateMin(range) {
  63. const minValue = labels.slice(range.value - 1, end.value);
  64. let newLabels = productChart.config.data.labels
  65. for(let i = 0; i < newLabels.length; i++){
  66. value = newLabels[i];
  67. if (minValue.includes(value)){
  68. productChart.config.data.datasets[0].backgroundColor=newBackgroundColor;
  69. }
  70. }
  71. end.min = range.value
  72. productChart.update();
  73. }
du7egjpx

du7egjpx1#

您可以使用backgroundColor选项的可脚本化选项。基于参数context.index(请参阅此处的doc:https://www.chartjs.org/docs/latest/general/options.html#scriptable-options),您可以在执行时期决定要使用的颜色。在下列程式码片段中,变更步进器值,图表会变更背景颜色。我已经使用了您的部分程式码。您可以使用滑杆或您正在使用的项目,而不使用步进器。
第一个

相关问题