首页 > 解决方案 > 如何更改 ChartJS 线段中的 pointBackgroundColor?

问题描述

我正在尝试更改图形线段部分中的 pointBackGround 颜色,但它似乎仅适用于borderColor。这是我的代码。有谁知道如何改变它们?顺便说一句,我正在使用 chart.js 版本 3.1.1。

const data = {
    datasets: [
        {
            type: 'line',
            label: `${props.stationSelected.selected.label2}`,
            borderColor: '#feb1c3',
            backgroundColor: '#feb1c3',
            pointRadius: 3,
            pointBackgroundColor: '#feb1c3',
            fill: false,
            data: hourlyData,
            tension: 0.5,
            segment: {
                borderColor: ctx => findEstimate(ctx, '#7c7c7c'), // this works
                pointBackgroundColor: ctx => findEstimate(ctx, '#7c7c7c'), // this does not work
            }
        },
    ],
}

const findEstimate = (ctx, value) => {
    const dt = ctx.p0.$context.raw.gageHeightDateTime
    const start = modalDataRaw.gageHeightDateTimeStart
    const stop = modalDataRaw.gageHeightDateTimeEnd
    if (dt >= start && dt <= stop) {
        return value
    }
}

在此处输入图像描述

标签: chartschart.js

解决方案


我已经这样解决了。只需根据您的任务更改上下文条件即可。

const test = (ctx, value) => (ctx.p1DataIndex >= showLast ? value : undefined)

const point = (ctx, trainCol, testCol) => ctx.index >= showLast ? testCol : trainCol


const data = {
labels: trainDates.map(val => val.format("DD-MM")),

datasets: [
  {
    label: "Test plot",
    data: values,
    borderColor: "rgb(75, 192, 192)",
    fill: false,
    pointStyle: "circle",
    pointBackgroundColor: ctx => point(ctx, "rgb(75, 192, 192)", "rgb(192,75,75)"),
    pointBorderColor: ctx => point(ctx, "rgb(75, 192, 192)", "rgb(192,75,75)"),
    segment: {
      borderColor: ctx => test(ctx, "rgb(192,75,75)"),
    },
  },
],}

结果图


推荐阅读