2

This must be a very easy and stupid question, but I have been unable to scale an HTML5 canvas to occupy all the available space at its parent, even when its the only element inside the parent div.

HTML:

<div style="padding: 5px; margin-bottom: 5px; height: 300px; border: 4px solid navy;">
    <canvas id="myChart"></canvas>
</div>

JS:

// Chart.js documentation example, nothing weird here
// Create canvas
var canvas = document.getElementById('myChart'),
    ctx = canvas.getContext('2d'),
    startingData = {
        labels: [1, 2, 3, 4, 5, 6, 7],
        datasets: [{
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            data: [65, 59, 80, 81, 56, 55, 40]
        }, {
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            data: [28, 48, 40, 19, 86, 27, 90]
        }]
    };

// Reduce the animation steps for demo clarity.
var optionChart = new Chart(ctx).Line(startingData, {
    animationSteps: 15
});


setInterval(function () {
    // Get a random index point
    var indexToUpdate = Math.round(Math.random() * startingData.labels.length);

    // Update one of the points in the second dataset
    optionChart.datasets[1].points[indexToUpdate].value = Math.random() * 100;

    optionChart.update();
}, 5000);

Here is my JSFiddle example. Any help?

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207

1 Answers1

2

http://jsfiddle.net/zntxn868/2/

You will need to calculate the width and height of the parent div and set the width property for canvas accordingly.

var wdt=parent.clientWidth-parseInt(parent.style.paddingLeft)-parseInt(parent.style.paddingRight);

var ht=parent.clientHeight-parseInt(parent.style.paddingTop)-parseInt(parent.style.paddingBottom);

canvas.setAttribute('height',ht+"px");
canvas.setAttribute('width',wdt+"px");

The reason I use clientWidth and clientHeight is, because you havent set the width of element explicitly.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
  • why is this the case? I always wondered. It would be much easier to place it if canvas would follow the css-layout – Johannes Reuter Jan 14 '15 at 08:52
  • you cant set width and height for canvas with css style. here is the reason http://stackoverflow.com/a/2588404/3556874 – Naeem Shaikh Jan 14 '15 at 08:53
  • What if I want to use em instead of px for parent size? I tried converting according to pxtoem.com, but then the canvas exceeds a little its parent: jsfiddle.net/zntxn868/5 Why? How to fix this? – Roman Rdgz Jan 15 '15 at 15:39