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

时间:2018-11-18 14:41:28

标签: javascript charts

        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?

1 个答案:

答案 0 :(得分:1)

您应该在每个fillStyle前用所需的颜色呼叫fillRect

        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();
                
            }
        });