0
votes

My use case is that I draw a chart with Chart.js, and when the user messes with certain options, I want to add or remove bars from the bar graph that I have drawn, and accordingly update the fixed width I had originally (programmatically) set on the chart.

Here's how I draw the chart:

function drawChart(barData) {
  oldData = barData;
  var ctx = document.getElementById("estimateChart").getContext("2d");
  ctx.canvas.width = getChartWidth(barData.length);
  var chartData = {
    labels: labels,
    datasets: [
      {
        highlightFill: "#888888",
        data: barData
      }
    ]
  };
  window.barFill = new Chart(ctx).Bar(chartData, {
    responsive: false
  });
  barFill.update();
}

Then when I update the chart, I do something like this

function updateChart(barData) {
  angular.forEach(oldData, function () {
    barFill.removeData();
  });
  oldData = barData;

  angular.forEach(barData, function (newBar, i) {
    barFill.addData([newBar], labels[i]);
  });
  barFill.chart.canvas.width = getWidth(barData);
  barFill.update();
}

Everything works fine... except that the width does not change on the updateChart call. When I look at the width on the barFill object, after the updateChart call, my changes were not saved.

I was unable to find anything about updating width in the Chart.js documentation, so I'm worried it may not be supported functionality out of the box. Do I just have to just create a new Chart object and replace the canvas element on the DOM whenever I want to change the width? That would be unfortunate since I'd like to keep the nifty Chart.js animations that come with the built-in update function.

1
Could you setup a Fiddle?Patel

1 Answers

1
votes

Instead of changing the barFill.chart.canvas.width. change barFill.scale.width.

function updateChart(barData) {
    angular.forEach(oldData, function () {
        barFill.removeData();
    });
    oldData = barData;

    angular.forEach(barData, function (newBar, i) {
        barFill.addData([newBar], labels[i]);
    });

    barFill.scale.width = getWidth(barData);
    barFill.resize().update();
}

It works even without the call to update() by the way, but I just kept it because it is the right way as per the documentation.

I would recommend resizing the container instead of the canvas element btw.


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