gpt4 book ai didi

javascript - 如何在chartjs中绘制多个不同颜色的矩形?

转载 作者:行者123 更新时间:2023-11-30 20:01:10 25 4
gpt4 key购买 nike

        Chart.pluginService.register({
beforeDraw: function (chart, easing) {

var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
const scales = chart.scales["x-axis-0"]
const leftMargin = scales.left;
const width = scales.width / 7;

ctx.save();

//as below, I can draw multiple rects
ctx.fillRect(leftMargin, chartArea.top, width, chartArea.bottom - chartArea.top);
ctx.fillRect(leftMargin + width * 2, chartArea.top, width, chartArea.bottom - chartArea.top);

//but I can't handle them seperately
ctx.fillStyle = "rgb(10, 10, 10);
ctx.restore();

}
});

上面的代码显示了我的问题是什么,我的问题是如何分别处理它们?我只是 chart.js 的初学者,我并不完全理解它的方法和工作原理。也许我需要创建一个新的上下文,或者将 id 添加到上面的代码中?

最佳答案

您应该在每个 fillRect 之前用所需的颜色调用 fillStyle

        Chart.pluginService.register({
beforeDraw: function (chart, easing) {

var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
const scales = chart.scales["x-axis-0"]
const leftMargin = scales.left;
const width = scales.width / 7;

ctx.save();

ctx.fillStyle = "rgb(10, 10, 10)"; // <--- do this before fillRect
ctx.fillRect(leftMargin, chartArea.top, width, chartArea.bottom - chartArea.top);
ctx.fillStyle = "rgb(20, 20, 20)"; // <--- do this before fillRect
ctx.fillRect(leftMargin + width * 2, chartArea.top, width, chartArea.bottom - chartArea.top);

ctx.restore();

}
});

关于javascript - 如何在chartjs中绘制多个不同颜色的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com