Is it possible to add a drop shadow to chart.js line chart?

后端 未结 2 675
渐次进展
渐次进展 2020-12-18 09:13

I\'m using chart.js to build a line chart. I was wondering if it is possible to add a drop shadow to the line chart I\'m displaying. To clarify I mean add a dro

2条回答
  •  误落风尘
    2020-12-18 09:34

    Extending the chart and overriding the draw function would be one (complicated) way to do this.

    An easier way would be to duplicate the chart canvas with all the other elements (grid lines, scale labels...) hidden, style the line differently (thicker and in a gray shade). Then position this duplicate canvas under and to the bottom and right of the original canvas.

    CSS

    .shadowParent {
        position: relative;
    }
    .shadowParent canvas.firstShadow {
        position: absolute;
        left: 10px;
        top: 30px;
        z-index: -1;
    }
    

    HTML

    Script

    ...
    
    var ctxShadow = document.getElementById("myChartShadow").getContext("2d");
    var dataShadow = JSON.parse(JSON.stringify(data));
    dataShadow.datasets[0].strokeColor = "rgba(220,220,220,0.2)"
    new Chart(ctxShadow).Line(dataShadow, {
        datasetStrokeWidth: 10,
        datasetFill: false,
        pointDot: false,
        showTooltips: false,
    });
    

    If your shadow isn't blurry enough you could add one more layer

    CSS

    .shadowParent canvas.secondShadow {
        position: absolute;
        left: 10px;
        top: 30px;
        z-index: -1;
    }
    

    HTML

    ...

    Script

    var ctxShadow2 = document.getElementById("myChartShadow2").getContext("2d");
    var dataShadow2 = JSON.parse(JSON.stringify(data));
    dataShadow2.datasets[0].strokeColor = "rgba(220,220,220,0.1)"
    new Chart(ctxShadow2).Line(dataShadow2, {
        datasetStrokeWidth: 20,
        datasetFill: false,
        pointDot: false,
        showTooltips: false,
        scaleFontColor: "rgba(0,0,0,0)",
        scaleLineColor: "rgba(0,0,0,0)",
        scaleShowGridLines: false,
        datasetFill: false,
    });
    

    Note that the scale aligns with the first shadow (it gives it a more 3D feel), but you can move it to the first layer if the scale is important (vs. this being more of an rough look kind of graph)


    Fiddle - http://jsfiddle.net/fjyj1021/


提交回复
热议问题