如何使用 ChartJS 通过 onclick 事件更改特定数据集的图表背景颜色

2023-12-24

// Set Chart Global Variables
let x_values = [0];
let y_values = [0];
let new_number = 0;
let index = 0;

// Intialize The Chart Canvas
let ctx = document.getElementById('chart_canvas').getContext('2d');

// Create New Line Chart
my_chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [x_values[0]],
    datasets: [{
      backgroundColor: [],
      fill: true,
      pointStyle: "circle",
      label: "Values",
      data: [y_values[0]]
    }]
  }
});

// ------ Local Functions ------

function add() {
  index = x_values.length;
  new_number += 10;

  my_chart.data.labels.push(index);
  x_values.push(index);

  my_chart.data.datasets.forEach((dataset) => {
    dataset.data.push(new_number);

    //The line below might be wrong since it is not changing the background color.
    dataset.backgroundColor.push("#88c0d080");
  });

  my_chart.update();
}

function subtract() {
  index = x_values.length;
  new_number -= 10;

  my_chart.data.labels.push(index);
  x_values.push(index);

  my_chart.data.datasets.forEach((dataset) => {
    dataset.data.push(new_number);

    //This line below might be wrong since it is not changing the background color.
    dataset.backgroundColor.push("#bf616a80");
  });

  my_chart.update();
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Testing Chart.js Line Chart</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
  <button type="button" onclick="add()" id="btnAdd">Add 10</button>
  <button type="button" onclick="subtract()" id="btnSubtract">Subtract 10</button>
  <canvas id="chart_canvas">Your browser does not support the HTML5 canvas tag.</canvas>
</body>

</html>

预期行为:

  • 当。。。的时候 ”Add 10" 按钮被点击,需要添加一个新的点条目backgroundColor充满 青色(#88c0d080).

  • 当。。。的时候 ”减10" 按钮被点击,需要添加一个新的点条目backgroundColor填充颜​​色为红色 (#bf616a80).

当前行为:

  • 仅改变点背景颜色,而不改变backgroundColor填色。

我们将非常感谢您的帮助。


您可以使用segment https://www.chartjs.org/docs/3.8.0/charts/line.html#segment添加新数据时动态更新的样式:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'orange',
      fill: true,
      segment: {
        backgroundColor: (ctx) => (ctx.p0.parsed.y > ctx.p1.parsed.y ? 'red' : 'teal')
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const c = new Chart(ctx, options);

document.getElementById('add').addEventListener('click', () => {
  c.data.labels.push(c.data.labels.length);
  c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] + 10)
  c.update()
});

document.getElementById('subb').addEventListener('click', () => {
  c.data.labels.push(c.data.labels.length);
  c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] - 10)
  c.update()
});
<body>
  <button id="add">
    Add 10
    </button>
  <button id="subb">
    Subtract 10
    </button>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ChartJS 通过 onclick 事件更改特定数据集的图表背景颜色 的相关文章

  • 响应式图像 - srcset 和尺寸属性 - 如何正确使用两者:基于设备像素比和基于视口的选择一起?

    到目前为止 我经常读到这个问题 并且它也发生在我自己的项目中 这里介绍一下我到目前为止所发现的关于 srcset 和 size 属性的内容 关于如何使用有两种不同的可能性srcset 属性 来源 w3c http w3c github io
  • 引导程序提前输入未填充承诺的响应

    我的引导程序预输入如下
  • Snap.svg - 停止在可悬停元素的子元素上重新触发悬停事件

    对于一个项目 我使用的 SVG 形状由背景多边形和背景多边形上方的一些文本 我已将其转换为路径 组成 我正在使用 Snap svg 为我的形状设置动画 当我将鼠标悬停在多边形上时 形状应该缩放到特定尺寸 包括其中的所有内容 鼠标移开时 形状
  • Draggable JS Bootstrap 模式 - 性能问题

    对于工作中的项目 我们在 JavaScript 中使用 Bootstrap Modal 窗口 我们想让一些窗口可移动 但我们遇到了 JQuery 的性能问题 myModal draggable handle modal header Exa
  • Bootstrap按钮加载+Ajax

    我正在使用 Twitter Bootstrap 的按钮加载状态 http twitter github com bootstrap javascript html buttons http twitter github com bootst
  • 如何将函数附加到弹出窗口关闭事件(Twitter Bootstrap)

    我做了一些搜索 但我只能认为我可以将事件附加到导致其关闭的按钮 https stackoverflow com questions 13205103 attach event handler to button in twitter boo
  • Jquery 数据表列总和

    我只是参考一下这个链接 https datatables net examples advanced init footer callback html了解如何获取 jquery 数据表中的列总计 但我已经完成了一半的项目 我在html页面
  • 尝试将数据存储在点击器网站中

    我正在尝试存储一个名为的变量score无论何时刷新 您都会一次又一次地使用它 我不明白的是它的代码是什么 我尝试了一些方法 但似乎都不起作用 这是我的答题器网站 但是当我尝试使用 JavaScript 来存储它时 它不起作用window o
  • 如何解决 Typescript 构建中的错误“找不到模块 'jquery'”

    我目前在 ts 文件的顶部有这个import require jquery 我这样做是因为我试图在我的打字稿文件中使用 jquery 但我似乎无法编译它 因为它返回标题中所述的错误 我正在使用 ASP NET CORE 脚本文件夹 tsco
  • 不可勾选的单选按钮与专有的复选框

    从 UI 角度来看 是拥有一组具有取消选中功能的单选按钮更好 还是拥有一组独占的复选框 意味着一次只能选中一个 更好 Update 我没想到对此会有如此负面的反应 如果我给出一个更接近其使用方式的示例 也许会有所帮助 我有一个充满数据绑定内
  • Vuejs 2:去抖动不适用于手表选项

    当我在 VueJs 中反跳此函数时 如果我提供毫秒数作为原语 它就可以正常工作 但是 如果我将其提供为对 prop 的引用 它会忽略它 这是道具的缩写版本 props debounce type Number default 500 这是不
  • Firebase 函数 onWrite 未被调用

    我正在尝试使用 Firebase 函数实现一个触发器 该触发器会复制数据库中的一些数据 我想观看所有添加的内容votes user vote 结构为 我尝试的代码是 const functions require firebase func
  • 在移动设备上滚动

    这个问题更多的是一个建议研究 我确实希望它对其他人有帮助 并且它不会关闭 因为我不太确定在哪里寻求有关此事的建议 在过去的 6 个月里 我一直在进行移动开发 我有机会处理各种设备上的各种情况和错误 最麻烦的是滚动问题 当涉及到在网站的多个区
  • 使用 Vue 的多模式组件

    我在 Vue 中实现动态模式组件时遇到问题 A common approach I follow to display a set of data fetched from the db is I dump each of the rows
  • 对于只触及我的工作表的 Google 表格脚本,收到“此应用程序未经验证”

    我正在编写一个 Google Sheets 脚本 我只想访问与 gs 文件关联的同一电子表格中的数据 似乎我应该有权在自己的电子表格中运行脚本 但是每当我运行一个函数时 我都会得到一个This app isn t verified信息 我该
  • 如何隐藏/禁用 Highcharts.js 中的图例框?

    我想问是否可以使用 HighCharts js 库隐藏图表中的所有图例框 var chart object chart renderTo render to type graph type colors graph colors title
  • 如何计算 3D 坐标的线性索引,反之亦然?

    如果我有一个点 x y z 如何找到该点的线性索引 i 我的编号方案是 0 0 0 是 0 1 0 0 是 1 0 1 0 是最大 x 维度 另外 如果我有一个线性坐标 i 我如何找到 x y z 我似乎无法在谷歌上找到这个 所有结果都充满
  • 从 FileReader 设置背景图像样式

    我正在寻找一种解决方案 允许我从文件上传输入中获取文件并通过设置 document body style backgroundImage 来预览它 以下代码用于在 Image 元素中显示预览 function setImage id tar
  • 如何在执行新操作时取消先前操作的执行?

    我有一个动作创建器 它会进行昂贵的计算 并在每次用户输入内容时调度一个动作 基本上是实时更新 但是 如果用户输入多个内容 我不希望之前昂贵的计算完全运行 理想情况下 我希望能够取消执行先前的计算并只执行当前的计算 没有内置功能可以取消Pro
  • Vue.js[vuex] 如何从突变中调度?

    我有一个要应用于 json 对象的过滤器列表 我的突变看起来像这样 const mutations setStars state payload state stars payload this dispatch filter setRev

随机推荐