Extend bar chart on Chart JS 2 into a new type of Chart

后端 未结 3 484
你的背包
你的背包 2021-02-06 18:31

I\'m actualy using Chart JS 2.0.1 to draw charts on a page.

My customers asked me to add a line in a bar chart so that they can see the limit they can\'t go over. Like

3条回答
  •  借酒劲吻你
    2021-02-06 19:10

    If this helps, I rewrite @Ptournem answer to be a valid 2.3.0 plugin with some sort of configutation

    Chart.plugins.register({
        config: {
            /** @type {rbg|rgba|hex}  Stroke color */
            strokeColor: "rgb(255, 0, 0)",
    
            /** @type {int}  Column width */
            lineWidth: 1,
        },
    
        afterDatasetsDraw: function(chartInstance, easing) {
            var value = chartInstance.config.lineAtValue;
    
            if (typeof value === 'undefined') return;
    
            var ctx   = chartInstance.chart.ctx,
                xaxis = chartInstance.scales['x-axis-0'],
                yaxis = chartInstance.scales['y-axis-0'];
    
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(xaxis.left, yaxis.getPixelForValue(value));
            ctx.lineWidth   = this.config.lineWidth;
            ctx.strokeStyle = this.config.strokeColor;
            ctx.lineTo(xaxis.right, yaxis.getPixelForValue(value));
            ctx.stroke();
            ctx.restore();
        },
    
        // IPlugin interface
        afterDatasetsUpdate: function(chartInstance) {},
        afterDraw: function(chartInstance, easing) {},
        afterEvent: function(chartInstance, event) {},
        afterInit: function(chartInstance) {},
        afterScaleUpdate: function(chartInstance) {},
        afterUpdate: function(chartInstance) {},
        beforeRender: function(chartInstance) {},
        beforeDatasetsDraw: function(chartInstance, easing) {},
        beforeDatasetsUpdate: function(chartInstance) {},
        beforeDraw: function(chartInstance, easing) {},
        beforeEvent: function(chartInstance, event) {},
        beforeInit: function(chartInstance) {},
        beforeUpdate: function(chartInstance) {},
        destroy: function(chartInstance) {},
        resize: function(chartInstance, newChartSize) {},
    });
    

提交回复
热议问题