我正在使用新的Chart.js并尝试完成一些自定义。在JS中使用过但在 Canvas 上是新手,我有点挣扎。我将尝试提供尽可能多的信息。

相关链接

  • JSBin工作演示
  • Chart.js 2.0 Documentation
  • Chart Screenshot - Current State
  • Chart Screenshot - Desired State


  • 代码-JSBin

    JavaScript

    /**
     * Chart.js Global Config
     */
    Chart.defaults.global.pointHitDetectionRadius = 5;
    window.count = 0;
    
    
    
    
    /**
     * Chart Data
     * @type {Object}
     */
    var lineChartData = {
      labels: ["", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
      datasets: [{
        label: "Students",
        data: [ 200, 250,220,180,290,300,370,350,200,280,260,190,210, 200 ],
        backgroundColor: "rgba(247,155,45,1.0)",
        borderColor: "rgba(247,155,45,1.0)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        pointBorderColor: "rgba(245,245,245,1)",
        pointBackgroundColor: "rgba(80,81,81,1)",
        pointHoverBorderWidth: 5,
        pointBorderWidth: 5,
        pointRadius: 8,
        pointHoverRadius: 9,
        pointHitRadius: 8,
      }]
    };
    
    
    
    /**
     * Init
     */
    window.onload = function() {
    
      var $chart = $('#chart');
    
      window.lineChart = new Chart($chart[0], {
        type: 'line',
    
        data: lineChartData,
    
        options: {
          showLines: true,
    
          // Legend
          legend : {
            display: false
          },
    
          // title
          title:{
            display:false,
            text:'Student Hours'
          },
    
          // Tooltips
          tooltips: {
            enabled: false,
          },
    
          // Scales
          scales: {
            yAxes: [{
              id: 'y-axis-0',
              gridLines: {
                display: true,
                lineWidth: 1,
                color: "rgba(255,255,255,0.85)"
              },
              ticks: {
                beginAtZero:true,
                mirror:false,
                suggestedMin: 0,
                suggestedMax: 500,
              },
              afterBuildTicks: function(chart) {
    
              }
            }],
            xAxes: [{
              id: 'x-axis-0',
              gridLines: {
                display: false
              },
              ticks: {
                beginAtZero: true
              }
            }]
          },
        }
      });
    
    };
    

    HTML

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.min.js"></script>
      <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    
    </head>
    <body>
      <div id="chartjs-container" class="chartjs-wrap">
        <canvas id="chart"></canvas>
      </div>
    </body>
    </html>
    

    CSS

    #chartjs-container {
      width:80%;
      margin:20px auto;
      position: relative;
    }
    
    .chartjs-wrap {
      background-color: rgba(250, 210, 162, 1.0);
    }
    
      canvas {
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    
        height:100%;
      }
    

    我想做什么
  • 删除沿y轴的网格线
  • 删除数据集的第一项和最后一项中与图表的左/右边缘相交的点
  • 插入y轴比例标签
  • 使x轴网格线重叠在线数据填充顶部


  • 屏幕截图

    当前状态
    javascript - Chart.js 2.0-如何更改 Canvas /图表元素的默认外观-LMLPHP

    所需状态(近似值)
    javascript - Chart.js 2.0-如何更改 Canvas /图表元素的默认外观-LMLPHP

    向我指出正确方向的任何帮助都会很棒。在 Canvas 的“检查元素”上是否有等效项?这些修复在CSS中将是微不足道的,但是我不确定如何调试。

    干杯

    最佳答案



    只需将displayoptions.scales.yAxes设置为false即可。这也将删除所有标签-我们将调用库方法在插件中绘制标签(不绘制y轴)(请参阅第4步)



    只需将数组传递给pointRadiuspointHoverRadius即可,而不是数字。以下数组将隐藏第一个和最后一个点(以及您的数据)

    ...
    pointRadius: [0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0],
    pointHoverRadius: [0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0],
    ...
    

    如果您的数据长度是动态的,则可能必须使用脚本来生成它。



    ticks.mirroroptions.scales.yAxes设置为true。然后,该插件(来自第4步)将只调用该库的draw方法进行缩放。



    为了使gridLines看起来像是在填充物上但在点之下,最简单的方法是将其绘制在填充物下并将填充物设置为稍微透明的值。
    backgroundColor: "rgba(247,155,45,0.4)",
    

    因为我们不希望它们从边缘开始,所以我们必须自己绘制gridLines。因此,将gridLines.displayoptions.scales.yAxes设置为false并注册以下插件
    Chart.pluginService.register({
        afterDraw: function (chart, easingDecimal) {
            var yScale = chart.scales['y-axis-0'];
            var helpers = Chart.helpers;
            var chartArea = chart.chartArea;
    
            // draw labels - all we do is turn on display and call scale.draw
            yScale.options.display = true;
            yScale.draw.apply(yScale, [chartArea]);
            yScale.options.display = false;
    
            yScale.ctx.save();
                // draw under the fill
            yScale.ctx.globalCompositeOperation = 'destination-over';
            // draw the grid lines - simplified version of library code
            helpers.each(yScale.ticks, function (label, index) {
                if (label === undefined || label === null) {
                    return;
                }
    
                var yLineValue = this.getPixelForTick(index);
                yLineValue += helpers.aliasPixel(this.ctx.lineWidth);
    
                this.ctx.lineWidth = this.options.gridLines.lineWidth;
                this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    
                this.ctx.beginPath();
                this.ctx.moveTo(chartArea.left + 40, yLineValue);
                this.ctx.lineTo(chartArea.right, yLineValue);
                this.ctx.stroke();
    
            }, yScale);
            yScale.ctx.restore();
        },
    })
    

    将为所有图表调用插件。如果要跳过某些图表的上述逻辑,则只需在options对象上设置一些属性,然后在运行逻辑之前检查它(例如,yAxis.options.customyAxis.options.display处于同一级别)

    如果要隐藏0和500标签,可以将ticks.callback设置为options.scales.yAxes,如下所示
    callback: function(value) {
      if (value !== 0 && value !== 500)
        return '' + value;
    },
    

    请注意,只要您的标度在建议的最小和建议的最大范围内,它就可以工作。如果您的数据超出这些范围,则必须使用scale属性。

    要使x轴标签背景为白色,只需将以下位添加到插件的afterDraw方法的末尾
    yScale.ctx.save();
    yScale.ctx.fillStyle = 'white';
    yScale.ctx.globalCompositeOperation = 'destination-over';
    yScale.ctx.fillRect(0, yScale.bottom, chartArea.right, chartArea.bottom);
    yScale.ctx.restore();
    

    它只是在 Canvas 内容下绘制一个白色矩形。由于您的背景色是通过CSS设置的,因此矩形位于背景色的顶部,并且所有内容都很有光泽。

    您还必须将背景色从.chartjs-wrap移至 Canvas (否则,底部会显示橙色边框)
    canvas {
        background-color: rgba(250, 210, 162, 1.0);
        ...
    

    您的JSBin的更新版本将应用以上所有内容-http://jsbin.com/parucayara/1/edit?output

    10-04 22:24
    查看更多