8

I'm trying to place a chart using Chart.js on a row with span6. Chart.js uses <canvas> and needs a height and width property. I've set the height to what I need and the width to 100% but it doesn't stretch to fill the div which is set to span6.

Any ideas?

<div class="row" style="padding-top: 20px;">
  <div class="span6">
    <div id="daily">
      <canvas id="daily-chart" width="100%" height="400px"></canvas>
    </div>
  </div>
</div>

2 Answers2

16

I managed to solve your problem!

Please check this jsFiddle.

Try resizing the panels to see it in action.

Basically, you call a function that responds to the resize of the window:

$(window).resize(respondCanvas);

that triggers a fetch of the width and height of the parent element that it is encapsulated in and then redraws your chart.

function respondCanvas() {
    c.attr('width', jQuery("#daily").width());
    c.attr('height', jQuery("#daily").height());
    //Call a function to redraw other content (texts, images etc)
    myNewChart = new Chart(ct).Bar(data, options);
}

You can adjust all tiny bits like your own IDs, classes, width and heights.

achudars
  • 1,486
  • 15
  • 25
0

in the JavaScript file where you add all the options for the chart

new Chart(ctx).Line(data, options );

//Boolean - If we want to override with a hard coded scale
    scaleOverride : true,
achudars
  • 1,486
  • 15
  • 25
  • also check this: http://stackoverflow.com/questions/11894607/how-do-i-dynamically-scale-the-html5-canvas-element – achudars Jul 19 '13 at 08:00
  • I previously set the options to null. To use them do I just create an options array? var options = [scaleOverride : true];? –  Jul 19 '13 at 08:02
  • Have you looked at this: http://www.chartjs.org/docs/ Line.defaults = { scaleOverride : true } – achudars Jul 19 '13 at 08:08
  • I had but I'm not sure how to implement it (I'm new to JS). Could you show me? I looked through the sample code but none of them implement options. –  Jul 19 '13 at 08:11
  • Thanks for that. Unfortunately the chart still isn't stretching to fill the width of the div. That option just sets the scale of the data on the chart, not the size of the chart itself. –  Jul 19 '13 at 08:22
  • check this: http://stackoverflow.com/questions/11368477/dynamically-resize-canvas-window-with-javascript-jquery – achudars Jul 19 '13 at 08:28
  • No luck. It's still only responding to the canvas width option and not stretching 100%. –  Jul 19 '13 at 08:31
  • Maybe you can share your own jsFiddle and we can look at it? – achudars Jul 19 '13 at 08:37
  • It seems that canvas can't be set to 100% (has to be a specific value). The links you shared were useful - I'm going to have to adjust the size in the JS. –  Jul 19 '13 at 08:44