【问题标题】:How to add background color between two lines in yAxis Chartjs如何在yAxis Chartjs中的两行之间添加背景颜色
【发布时间】:2018-03-15 14:09:10
【问题描述】:

如何在 chartjs 的 Y 轴上的两条线之间添加背景颜色 如果你检查了这个数字,我需要能够做这样的事情 在两条线之间设置颜色,首先是橙色,然后是蓝色或其他颜色, 我检查了官方文档,但我没有找到任何东西。

这也是我的chartjs配置

 this.options = {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          xAxes: [
            {
              gridLines: {
                display: true,
                color: chartjs.axisLineColor,
              },
              ticks: {
                fontColor: chartjs.textColor,
              },
            },
          ],
          yAxes: [
            {
              gridLines: {
                display: true,
                color: chartjs.axisLineColor,
              },
              ticks: {
                fontColor: chartjs.textColor,
              },
            },
          ],
        },
        legend: {
          labels: {
            fontColor: chartjs.textColor,
          },
        },
      };

【问题讨论】:

    标签: javascript chart.js chartjs-2.6.0


    【解决方案1】:

    你必须注册自己的plugin才能在绘制图表线之前填充chartArea:

    Chart.pluginService.register({
      beforeDraw: function (chart, easing) {
        if (chart.config.options.fillColor) {
          var ctx = chart.chart.ctx;
          var chartArea = chart.chartArea;
          ctx.save();
          ctx.fillStyle = chart.config.options.fillColor;
          ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
          ctx.restore();
        }
      }
    });
    
    var chartData = {
      labels: ['a', 'b', 'c', 'd'],
      datasets: [{
        label: 'value',
        backgroundColor: 'rgba(255, 0, 255, 0.8)',
        borderColor: 'blue',
        data: [30, 50, 25, 10]
      }]
    };
    
    var ctx = document.getElementById("myChart").getContext("2d");
    var myBar = new Chart(ctx, {
      type: 'line',
      data: chartData,
      options: {
      	scales: {
        	yAxes: [{ ticks: { max: 60 } }]
        },
      	legend: { display: false },
    		fillColor: 'rgba(255, 128, 0, 0.8)',
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    
    <canvas id="myChart" height="300" width="500"></canvas>

    【讨论】:

    • 正是我想做的,我把它改成了ctx.fillStyle = chart.config.options.fillColor; ctx.fillRect(chartArea.left, chartArea.top+ (step), chartArea.right - chartArea.left, (chartArea.bottom - chartArea.top)/4);谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多