Pascut
Pascut

Reputation: 3434

Chart.js v2 overwrite draw function

I'm using chart.js 2.6.0, which is the latest version.

I'm trying to overwrite the bar charts in order to make the corners rounded. I found this script: https://github.com/jedtrow/Chart.js-Rounded-Bar-Charts/blob/master/Chart.extentions.js and it works good.

I created a new graph option: "is_curved" because I have multiple graphs on the same page and I want to make rounded corners only for some of them.

The problem in my case is that if I'm using the following code, all the charts have rounded corners:

Chart.elements.Rectangle.prototype.draw = function() {
    //code to make corners rounded
}

The function:

Chart.elements.Rectangle.prototype.draw

Is called on all the charts. I want it to be executed only when the option "is_curved" is set to true. So I tried:

Chart.elements.Rectangle.prototype.draw = function() {
    if(!this._chart.options.is_curved) {
        return;
    }
    //code to make corners rounded
}

But this is still wrong because the graphs that doesn't have the "is_curved" option set to true are empty, I guess that the fact that I call the .draw method removes all the existing functionality, even if I don't add new functionality for them.

Any idea how can I set the draw function to work only for the charts with "is_curved" option set to true? Thanks.

Upvotes: 2

Views: 2166

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

change this line of code:

var cornerRadius = 5;

to this :

var cornerRadius = this._chart.options.is_curved ? 5 : 0;

this will set bar­'s corner radius to 5 , if the is_curved property is set to true for any particular chart, otherwise will set to 0 .

see - working example on JSFiddle

Upvotes: 4

Related Questions