作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!