Search code examples
chart.jsdropshadowbevelled

Styling Bars and Lines with Chart.js


We have been using Chart.js for several months now and like the power it gives us with ease of programming. One of the things we would like to start adding to the charts produced from Chart.js is a little nicer styling of the charts we generate. Most of the charts we are using are bar charts, with a few line charts thrown in.

When I use the term "styling" what I am really talking about is making the bars or lines look a little nicer. Specifically I would like to add a drop shadow behind the bar and line charts, and maybe even a bevel to the bars.

I've looked through many questions, and can't seem to find what I am looking for. I've also done some experimenting myself by modifying the Chart.js file to add a drop shadow and blur to the javascript, but I'm not getting it added in the correct place. I put these changes inside of the Chart.Element.extend draw function:

ctx.shadowColor = '#000';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 8;
ctx.shadowOffsetY = 8;

I put it right before the ctx.fill() and it almost does what I want. The result is I get a drop shadow that looks pretty good on both the bar and line charts I am drawing, but I also get a drop shadow on the labels for the x and y axes, which does not look good. I'd like to have the drop shadow on just the bars and the lines, not on the labels.

Any help you can provide would be greatly appreciated. I am not experienced with javascript, but have been able to pull off quite a bit of coding I wouldn't otherwise be able to do without the help of everyone on Stack Overflow.


Solution

  • Adding a Drop Shadow for Line Charts

    You can extend the line chart type to do this


    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 originalStroke = ctx.stroke;
            ctx.stroke = function () {
                ctx.save();
                ctx.shadowColor = '#000';
                ctx.shadowBlur = 10;
                ctx.shadowOffsetX = 8;
                ctx.shadowOffsetY = 8;
                originalStroke.apply(this, arguments)
                ctx.restore();
            }
        }
    });
    

    and then

    ...
    var myChart = new Chart(ctx).LineAlt(data, {
        datasetFill: false
    });
    

    Fiddle - https://jsfiddle.net/7kbz1L4t/