Chart.js: Chartjs ctx.rotate and ctx.translate and drawn lines

Created on 19 Jul 2016  路  3Comments  路  Source: chartjs/Chart.js

I'm using ChartJS v2,
I already have the text above the bars in my graph would now like to turn them, how can I do this ?

And also it is possible to add a line in a espefico value in the graph ?

Like this:

https://s31.postimg.org/kx1z1v17v/imgpsh_fullsize.png

My simple code to show de value on top of the bar:

animation: {
                    onComplete: function () {
                        var chartInstance = this.chart;
                        var ctx = chartInstance.ctx;
                        ctx.textAlign = "center";
                      ctx.font = "bold 20px Arial";
                      ctx.fillStyle = "white";                            
                        Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
                            var meta = chartInstance.controller.getDatasetMeta(i);
                            Chart.helpers.each(meta.data.forEach(function (bar, index) {
                                ctx.fillText(dataset.data[index], bar._model.x, bar._model.y - 30);
                            }),this)
                        }),this);
                    }
                }
support

Most helpful comment

Try this

animation: {
  onComplete: function () {
    var chartInstance = this.chart;
    var ctx = chartInstance.ctx;
    ctx.textAlign = "center";
    ctx.font = "bold 20px Arial";
    ctx.fillStyle = "white";                            
    Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
      var meta = chartInstance.controller.getDatasetMeta(i);
      Chart.helpers.each(meta.data.forEach(function (bar, index) {
        ctx.save();
        // Translate 0,0 to the point you want the text
        ctx.translate(bar._model.x, bar._model.y - 30);

        // Rotate context by -90 degrees
        ctx.rotate(-0.5 * Math.PI);

        // Draw text
        ctx.fillText(dataset.data[index], 0, 0);
        ctx.restore();
      }),this)
    }),this);
  }
}

All 3 comments

Try this

animation: {
  onComplete: function () {
    var chartInstance = this.chart;
    var ctx = chartInstance.ctx;
    ctx.textAlign = "center";
    ctx.font = "bold 20px Arial";
    ctx.fillStyle = "white";                            
    Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
      var meta = chartInstance.controller.getDatasetMeta(i);
      Chart.helpers.each(meta.data.forEach(function (bar, index) {
        ctx.save();
        // Translate 0,0 to the point you want the text
        ctx.translate(bar._model.x, bar._model.y - 30);

        // Rotate context by -90 degrees
        ctx.rotate(-0.5 * Math.PI);

        // Draw text
        ctx.fillText(dataset.data[index], 0, 0);
        ctx.restore();
      }),this)
    }),this);
  }
}

Thanks work perfect :)

@etimberg Works perfectly!!

Was this page helpful?
0 / 5 - 0 ratings