charts - 如何在Charts.js的每一行末尾添加文本-LMLPHP

我如何使用 Charts.js 在每一行末尾添加文本,例如第97、95等。任何帮助将是巨大的。我尝试了文档并进行了谷歌搜索。

最佳答案

您可以在每行的结尾处extend线 Controller 绘制系列标签:

var chartData = {
  datasets: [{
    label: 'serie1',
    backgroundColor: 'rgba(255, 255, 255, 0.0)',
    borderColor: 'rgba(0, 119, 290, 0.6)',
    data: [{x: 1, y: 10}, {x: 2, y: 12}, {x: 3, y: 18}, {x: 4, y: 5}, {x: 5, y: 25}, {x: 6, y: 30}]
  },
  {
    label: 'serie2',
    backgroundColor: 'rgba(255, 255, 255, 0.0)',
    borderColor: 'rgba(120, 0, 190, 0.6)',
    data: [{x: 1, y: 8}, {x: 2, y: 9}, {x: 3, y: 16}, {x: 4, y: 8}, {x: 5, y: 12}, {x: 6, y: 20}]
  },
  {
    label: 'serie3',
    backgroundColor: 'rgba(255, 255, 255, 0.0)',
    borderColor: 'rgba(0, 200, 10, 0.6)',
    data: [{x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 26}, {x: 4, y: 18}, {x: 5, y: 19}, {x: 6, y: 10}]
  }]
};

var originalController = Chart.controllers.line;
Chart.controllers.line = Chart.controllers.line.extend({
  draw: function() {
    originalController.prototype.draw.call(this, arguments);
    drawLabels(this);
  }
});

function drawLabels(t) {
	ctx.save();
  ctx.font = Chart.helpers.fontString(12, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
  ctx.fillStyle = 'red';
  ctx.textBaseline = 'bottom';

  var chartInstance = t.chart;
  var datasets = chartInstance.config.data.datasets;
  datasets.forEach(function(ds, index) {
    var label = ds.label;
    var meta = chartInstance.controller.getDatasetMeta(index);
    var len = meta.data.length-1;
    //console.log(ds, meta.data[len]._model);
    var xOffset = meta.data[len]._model.x+10;
    var yOffset = meta.data[len]._model.y;
    ctx.fillText(label, xOffset, yOffset);
  });
  ctx.restore();
}


var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: {
  	legend: { display: false },
    scales: {
      xAxes: [{
      	type: 'linear',
        scaleLabel: { display: true, labelString: 'x' }
      }],
      yAxes: [{
        ticks: { min: 0 },
        scaleLabel: { display: true, labelString: 'y' }
      }]
    },
    layout: {
      padding: {
        left: 0,
        right: 60,
        top: 20,
        bottom: 0
      }
    }
  }
});
#myChart {
  border: solid 1px rgba(255, 0, 0, 0.5);
}
<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>


这是一个jsfiddle:http://jsfiddle.net/beaver71/q62yv516/

关于charts - 如何在Charts.js的每一行末尾添加文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49386612/

10-11 11:42