0

I'm using Canvas chart and what I want to achieve is to put volume number (some text) in the center of a donut chart. I'm also using AngularJS.

This is my code:

$scope.fill = function(chart) {
        var chart = $('#doughnut');

        console.log(chart);
        var width = chart[0].width,
            height = chart[0].height,
            ctx = chart[0].getContext("2d");

        console.log(height);

        ctx.restore();
        var fontSize = (height / 300).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";

        var text = $scope.volume + ' PLN';
        console.log(text);
        // text = text.split('').splice(3, 0, ' ').join() + ' PLN'; // to do sth like this

        var textX = Math.round((width - ctx.measureText(text).width) / 2),
            textY = height / 2;
        console.log(textY);
        console.log(textX);
        ctx.fillText(text, textX, textY);
        console.log(ctx.fillText(text, textX, textY));
        ctx.save();
    }();

All console.logs give me exactly the right value. However, 'fillText' and 'save' do not have any effect on page. What may be wrong?

Hubert Kubiak
  • 607
  • 1
  • 7
  • 30
  • what value does fontSize have in the console? Try using a fixed value in pixels to eliminate. You can btw use textAlign="center" instead of calculating using measureText. Then calc textX = width/2. –  Mar 08 '17 at 04:49
  • @K3N fontSize have value of 2.00 so I guess it's right. The problem is it worked when I used the solution like here: http://stackoverflow.com/questions/38724876/how-to-add-text-in-centre-of-the-doughnut-chart-using-chart-js but then it applied to all the charts (which I do not understand as I put it just in the controller responsible for one view). So now I try to write a function which I will initiate only on creating one particular chart. – Hubert Kubiak Mar 08 '17 at 08:23
  • I discovered that the filling text color was white so it wouldn't be noticed anyway as the background is so also. But when I changed it for blue, it anyway didn't occur. When I set the function as ng-click of the canvas, it works each second time I click but when I do anything later (leave hover out of canvas or just click somewhere on any chart element) it disappears. Then I can click and show it again. – Hubert Kubiak Mar 08 '17 at 08:55
  • Ok, I did it other way. I used the solution from the link above but added one condition: 'if (chart.config.options.elements.center)' and added this option to the chart config. Now it just applies to the charts I specify so. – Hubert Kubiak Mar 08 '17 at 09:17

0 Answers0