如何将用Chart.js创建的折线图的线条设置为渐变?

sh7euo9m  于 2024-01-07  发布在  Chart.js
关注(0)|答案(1)|浏览(300)


的数据
我试图使用Chart.js在图像中获取图表。但我找不到如何制作线条渐变。我想做的是在线条向上时使用rgba(249,65,68,1)颜色,在线条向下时使用rgba(51,51,51,1)颜色。

  1. <script>
  2. document.addEventListener("DOMContentLoaded", function () {
  3. var dataValues = [18, 20, 18, 15, 12, 8, 11, 22];
  4. var data = {
  5. labels: Array.from({ length: dataValues.length }, (_, index) => ""),
  6. datasets: [
  7. {
  8. label: "",
  9. borderColor: "rgba(249, 65, 68, 1)",
  10. data: dataValues,
  11. pointBackgroundColor: "rgba(249, 65, 68, 1)",
  12. fill: false,
  13. },
  14. ],
  15. };
  16. var ctx = document.getElementById("timeChart").getContext("2d");
  17. var myLineChart = new Chart(ctx, {
  18. type: "line",
  19. data: data,
  20. options: {
  21. datasetFill: true,
  22. showTooltips: false,
  23. maintainAspectRatio: false,
  24. responsive: true,
  25. plugins: {
  26. legend: {
  27. display: false,
  28. },
  29. },
  30. },
  31. });
  32. });

字符串

kjthegm6

kjthegm61#

根据文档,您必须添加此功能:

  1. let width, height, gradient;
  2. function getGradient(ctx, chartArea) {
  3. const chartWidth = chartArea.right - chartArea.left;
  4. const chartHeight = chartArea.bottom - chartArea.top;
  5. if (!gradient || width !== chartWidth || height !== chartHeight) {
  6. // Create the gradient because this is either the first render
  7. // or the size of the chart has changed
  8. width = chartWidth;
  9. height = chartHeight;
  10. gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
  11. gradient.addColorStop(0, "rgba(51, 51, 51, 1)");
  12. gradient.addColorStop(0.5, "rgba(249, 65, 68, 1)");
  13. }
  14. return gradient;
  15. }

字符串
然后你会在数据集内返回它:

  1. datasets: [
  2. {
  3. label: 'Dataset 1',
  4. data: Utils.numbers(NUMBER_CFG),
  5. borderColor: function(context) {
  6. const chart = context.chart;
  7. const {ctx, chartArea} = chart;
  8. if (!chartArea) {
  9. // This case happens on initial chart load
  10. return;
  11. }
  12. return getGradient(ctx, chartArea);
  13. },
  14. },
  15. ]


下面是这个例子的link

展开查看全部

相关问题