Tommy Petersson
Tommy Petersson

Reputation: 95

How to place extra text on canvas (not using HTML) beside chart?

I'm using chart.js ver.2 to make different charts. There are some fixed places where you can place info, like in title and legend. But if I want to put some text in "unused areas" of the canvas it doesn't seem to work by just using standard self.Context.fillText calls after animation onComplete. Is writing a chart plugin the only way? If so, any help with that?

I have a function called on the onComplete event that among other things enables a print button. Since the print function copies the canvas I need the info to be part of the canvas and not done as HTML.

Context is in self.Context. I just put in some lines for test:

self.Context.fillStyle = "blue";
self.Context.font = "bold 16px Arial";
self.Context.fillText("Tommy", 10, self.chart.canvas.height - 50);

...but nothing is shown. So it seems chart.js "owns" the canvas and I would need to extend chart.js functionality with a plugin for that.

Pie

There's a lot of white spice on this (test data) chart canvas and it would be nice to be able to use that for giving some more info to the users.

Is a chart.js plugin the only non-HTML way? If so, any usable example to help me write one?

Upvotes: 0

Views: 379

Answers (1)

Tommy Petersson
Tommy Petersson

Reputation: 95

I found out that you can create an Extend function for each of the different chart types (for instance you may want to place the text at different places depending on chart type), here's an example for a line chart:

            let myLineExtend = Chart.controllers.line.prototype.draw;
            Chart.helpers.extend(Chart.controllers.line.prototype, {
                draw: function () {
                    myLineExtend.apply(this, arguments);
                    self.Context.save();
                    self.Context.fillStyle = "#032f55";
                    var ctx = self.Context;
                    ctx.textAlign = "left";
                    ctx.textBaseline = "middle";
                    ctx.font = "12px arial";
                    ctx.fillText("Random text", (self.chart.canvas.width * 1) / 10, (self.chart.canvas.height * 3) / 4);
                    self.Context.restore();
                }
            });

Upvotes: 0

Related Questions