Chartjs doughnut segment pattern

1.1k Views Asked by At

I'm working on a project that's already heavily invested in the Chart.js library, so I'd rather not have to use something else if at all possible.

A new requirement has come through for chart segments to have patterns, for the company's accessibility requirements. I can ask them to explore different avenues if this is too difficult, but I said I'd see if there's a relatively easy way of getting this working first.

So, is there a relatively easy way to fill each doughnut segment with a different pattern?

1

There are 1 best solutions below

0
On

Figured out I can just create a canvas pattern and pass it through to the Chart.js data object for each segment's color property, as below. It's a bit dirty, but it works and will suffice!

// Create a temporary canvas and fill it with a grid pattern
var patternCanvas = document.createElement("canvas"),
    patternContext = patternCanvas.getContext("2d");

patternCanvas.width = 10;
patternCanvas.height = 10;

patternContext.beginPath();
patternContext.fillStyle = "#f2cc1b";
patternContext.fillRect(0, 0, 10, 10);
patternContext.strokeRect(0.5, 0.5, 10, 10);
patternContext.stroke();

// Store the pattern for referencing in the Chart.js data
var pattern = patternContext.createPattern(patternCanvas, "repeat");

// Pass this through to the chart
var data = [
    {
        value: 30,
        color: pattern,
        label: "Some data label"
    }
];