J. Doe J. Doe - 4 months ago 12
HTML Question

Javascript chart fills up the entire browser window

I'm creating my first chart using chart.js.

The chart is displayed like I want it to except for the fact that it always fills up the entire browser screen.

I have tried setting the chart dimensions to 100 but it doesn't seem to work.

I have created a jsFiddle that showcases my issue:

https://jsfiddle.net/1q5oej4q/

Also, here's the code if you wanna view it here:

Javascript:

$(function() {
displayLineChart();

function displayLineChart() {
var data = {
labels: ['first', 2, 3, 4, 5, 6, 7, 8, 9, 10],
datasets: [{
label: "Prime and Fibonacci",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
}, {
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}]
};

var chart = document.getElementById("lineChart");
chart.width = 100;
chart.height = 100;

var ctx = document.getElementById("lineChart").getContext("2d");
ctx.canvas.width = 100;
ctx.canvas.height = 100;
var options = {};
var lineChart = new Chart(ctx, {
type: 'line',
data: data,
});
}
});


Html:

<canvas id="lineChart">
</canvas>

Answer

Wrap it in a <div>, then size that:

CSS:

#wrapper {
  width: 400px;
  height: 500px;
}

HTML:

<div id="wrapper">
    <canvas id="lineChart">
    </canvas>
</div>

jsFiddle.