如何使用 Chart.js 将图表的背景色设置为渐变色
How to make the background color of the chart as gradient using Chart.js
我正在尝试在 React 中使用 Chart.js 制作折线图。
我没有使用 DOM 创建和达到 canvas。
我可以安排背景颜色,但我只想将其设置为渐变。我该怎么做?
我的代码如下:
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;
输出如下:
https://i.stack.imgur.com/D5lwg.png
您可以使用 canvas“createLinearGradient”方法。
文档:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient,
https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient/addColorStop
示例: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)"
}
]
};
我正在尝试在 React 中使用 Chart.js 制作折线图。 我没有使用 DOM 创建和达到 canvas。 我可以安排背景颜色,但我只想将其设置为渐变。我该怎么做?
我的代码如下:
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;
输出如下: https://i.stack.imgur.com/D5lwg.png
您可以使用 canvas“createLinearGradient”方法。
文档: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient, https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient/addColorStop
示例: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)"
}
]
};