[Chartjs]-How to customize chart js Bar chart shape?

1👍

One way to get the triangles is to do a stacked chart, and add a line graph on top. To keep it reactive you would need to dynamically resize the pointRadius on the line data.

https://jsfiddle.net/0mcd5s13/3/

Or on line 4640 of chart.js you can change element_rectangle draw function to this:

draw: function() {
        var ctx = this._chart.ctx;
        var vm = this._view;
        var rects = boundingRects(vm);
        var outer = rects.outer;
        var inner = rects.inner;

        //ctx.fillStyle = vm.backgroundColor;
        //ctx.fillRect(outer.x, outer.y, outer.w, outer.h);

        if (outer.w === inner.w && outer.h === inner.h) {
            return;
    }
    
    let offset = outer.w / 2;

        ctx.save();
    ctx.beginPath();
    
    ctx.moveTo(outer.x, outer.y);
    ctx.lineTo(outer.x, outer.y + outer.h);
    ctx.lineTo(outer.x + offset, outer.y + outer.h + offset);
    //ctx.lineTo(outer.x + offset, outer.y + outer.h);
    ctx.lineTo(outer.x + outer.w, outer.y + outer.h);
    ctx.lineTo(outer.x + outer.w, outer.y);
    ctx.lineTo(outer.x + offset, outer.y - offset);
    ctx.lineTo(outer.x, outer.y);
    ctx.stroke();


        //ctx.rect(outer.x, outer.y, outer.w, outer.h);
         ctx.clip();
         ctx.fillStyle = vm.borderColor;
        // ctx.rect(inner.x, inner.y, inner.w, inner.h);
         ctx.fill('evenodd');
        ctx.restore();
    },

which yields this:
chart

more likely to import chart.js from a source, you will need make your own type of chart as an extension of bar chart.

(function(Chart) {
  var helpers = Chart.helpers;

    Chart.defaults.triBar = {
        hover: {
            mode: "label"
        },
    dataset: {
      categoryPercentage: 0.8,
      barPercentage: 0.9
    },
        scales: {
            xAxes: [{
                type: "category",
                // grid line settings
                gridLines: {
                    offsetGridLines: true
                }
            }],
            yAxes: [{
                type: "linear"
            }]
        }
    };


  Chart.controllers.triangleBar = Chart.controllers.bar.extend({           
    
    //  
    //  extend element_rectangle draw function here
    //

  });    
}).call(this, Chart);

Leave a comment