Chart.js — Color Options

Image for post
Image for post
Photo by Robert Katzki on Unsplash

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Indexable Options

Indexable options are options that are arrays.

For example, we can write:

We have the backgroundColor and borderColor options which are indexable options.

The values are set on the bars according to the bars’ indexes.

Option Context

The option content gives us contextual information when we resolving options.

They are used only with scriptable options.

The properties of the context object include:

  • chart — the chart we’re modifying
  • dataIndex — index of the current data
  • dataset — dataset at index datasetIndex
  • datasetIndex — index of the current dataset
  • hovertrue if hovered

Colors

We can set the color options in various ways.

One way is to change the background color to a fill pattern.

For example, we can write:

We created an Image instance and we called the createPattern method of the context to create a fill pattern that we can use in our chart bars.

'repeat' makes the pattern repeat to fill the bars.

Then we set that as the value of backgroundColor and it’ll show as the bar color.

Also, we can use the Patternomaly library to create our patterns.

We can use it with the following HTML:

Then we can create a chart by writing:

The pattern.draw method comes from the Patternomaly library.

'square' makes a square repeating pattern.

'circle' makes a circle repeating pattern.

And 'diamond' makes a diamond repeating pattern.

The 2nd argument is the background color.

Now we should see bars with the given background patterns.

Conclusion

We can create charts with various color options with Chart.js.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store