最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make the background color of the chart as gradient using Chart.js - Stack Overflow

programmeradmin3浏览0评论

I am trying to make a line chart using Chart.js in React. I did not use DOM to create and reach canvas. I can arrange the background color but I just want to make it as gradient. How can I do that?

My codes below:

import React from "react";
import { Line } from "@reactchartjs/react-chart.js";

const data = {
  labels: ["day1", "day2", "day3", "day4", "day5", "day6"],
  datasets: [
    {
      label: "Your BMI",
      data: [28.3, 28, 27, 27.6, 25, 25.6],
      fill: true,
      backgroundColor: "rgba(10,10,10,.2)",
      borderColor: "rgba(152,222,217,0.2)"
    }
  ]
};




const options = {
  scales: {
    yAxes: [
      {
        ticks: {
          beginAtZero: true
        }
      }
    ]
  }
};

const LineChart = () => (
  <>
    <Line data={data} options={options} />
  </>
);

export default LineChart;

output

I am trying to make a line chart using Chart.js in React. I did not use DOM to create and reach canvas. I can arrange the background color but I just want to make it as gradient. How can I do that?

My codes below:

import React from "react";
import { Line } from "@reactchartjs/react-chart.js";

const data = {
  labels: ["day1", "day2", "day3", "day4", "day5", "day6"],
  datasets: [
    {
      label: "Your BMI",
      data: [28.3, 28, 27, 27.6, 25, 25.6],
      fill: true,
      backgroundColor: "rgba(10,10,10,.2)",
      borderColor: "rgba(152,222,217,0.2)"
    }
  ]
};




const options = {
  scales: {
    yAxes: [
      {
        ticks: {
          beginAtZero: true
        }
      }
    ]
  }
};

const LineChart = () => (
  <>
    <Line data={data} options={options} />
  </>
);

export default LineChart;

output

Share Improve this question edited Jun 29, 2022 at 12:38 Apostolos 10.5k5 gold badges32 silver badges44 bronze badges asked Feb 10, 2021 at 14:19 Yagnur TetikcanYagnur Tetikcan 231 gold badge1 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You can use the canvas "createLinearGradient" method.

Docs: https://developer.mozilla/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient, https://developer.mozilla/en-US/docs/Web/API/CanvasGradient/addColorStop

Example: https://codepen.io/alexgill/pen/MWbjXOP

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(10,10,10,.2)');   
gradient.addColorStop(1, 'rgba(255,255,255,1)');


const data = {
  labels: ["day1", "day2", "day3", "day4", "day5", "day6"],
  datasets: [
    {
      label: "Your BMI",
      data: [28.3, 28, 27, 27.6, 25, 25.6],
      backgroundColor : gradient,
      borderColor: "rgba(152,222,217,0.2)"
    }
  ]
};
发布评论

评论列表(0)

  1. 暂无评论