Chartjs-Chartjs doughnut segment pattern

1👍

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"
    }
];

Leave a comment