[Chartjs]-How can I draw dotted line using chartjs?

7👍

In Chart.js 2.1+, use the borderDash option within your dataset. It takes an array of two numbers. See this codepen

6👍

For dotted lines use borderDash and borderCapStyle. The following example creates a dotted line (3px diameter):

data: {
  datasets: [
    {
        data           : data,
        borderWidth    : 3, // set diameter of dots here
        borderColor    : '#ccc',
        fill           : false,
        pointRadius    : 0,
        borderDash     : [0,6], // set 'length' of dash/dots to zero and
                                // space between dots (center to center)
                                // recommendation: 2x the borderWidth
        borderCapStyle : 'round' // this is where the magic happens
    }
  ]
}

Output

Output

Output (better contrast for demonstration)
enter image description here

4👍

Drawing a Dotted Line

You don’t need to extend the chart, but it would be cleaner to do it that way.


Preview

enter image description here

Script

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function () {
        Chart.types.Line.prototype.initialize.apply(this, arguments);

        var ctx = this.chart.ctx;
        var originalBezierCurveTo = ctx.bezierCurveTo;
        ctx.bezierCurveTo = function () {
            ctx.setLineDash([10, 10]);
            originalBezierCurveTo.apply(this, arguments)
        }
    }
});

...

new Chart(ctx).LineAlt(chartData);

Fiddle – https://jsfiddle.net/ahj6u14e/


Note – the alternative would be to just override bezierCurveTo using the chart object.

This works because bezierCurveTo is only used to draw the line. If you wanted to do this for straight lines it wouldn’t work because lineTo is used for other stuff (axis, grid lines…)

Chart.js 2.0 had a borderDash option when I last checked (see https://stackoverflow.com/a/31428640/360067)

Leave a comment