I'm designing a dashboard using boostrap grid. Some cells have a canvas
in it and I want to force it to match the size of its parent. I'm basically calculating the size this way:
var parent = canvas.parentElement;
if (parent.style) {
var parentStyle = window.getComputedStyle(parent, null);
var w = parseFloat(parentStyle.width) - (parseFloat(parentStyle.paddingLeft) + parseFloat(parentStyle.paddingRight) + parseFloat(parentStyle.borderLeftWidth) + parseFloat(parentStyle.borderRightWidth));
var h = parseFloat(parentStyle.height) - (parseFloat(parentStyle.paddingTop) + parseFloat(parentStyle.paddingBottom) + parseFloat(parentStyle.borderTopWidth) + parseFloat(parentStyle.borderBottomWidth));
canvas.width = w;
canvas.height = h;
}
However, when I resize the page, the canvas, or the cell seems to keep growing in height and I don't understand why.
Run the following example in "full page" and resize the window horizontally. You'll see how the cells keep growing in height.
function resizeCanvas(canvas) {
var parent = canvas.parentElement;
if (parent.style) {
var parentStyle = window.getComputedStyle(parent, null);
var w = parseFloat(parentStyle.width) - (parseFloat(parentStyle.paddingLeft) + parseFloat(parentStyle.paddingRight) + parseFloat(parentStyle.borderLeftWidth) + parseFloat(parentStyle.borderRightWidth));
var h = parseFloat(parentStyle.height) - (parseFloat(parentStyle.paddingTop) + parseFloat(parentStyle.paddingBottom) + parseFloat(parentStyle.borderTopWidth) + parseFloat(parentStyle.borderBottomWidth));
canvas.width = w;
canvas.height = h;
}
}
function paintOnCanvas(canvas) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = "20px Verdana";
ctx.fillStyle = "black";
ctx.fillText("Paint on Canvas", 10, 50);
}
document.addEventListener("DOMContentLoaded", function(event) {
paintOnCanvas(document.getElementById("canvas"));
});
window.addEventListener('resize', function(event) {
resizeCanvas(document.getElementById("canvas"));
paintOnCanvas(document.getElementById("canvas"));
});
canvas {
background-color: #ce8483;
width: 100%;
height: 100%;
}
.col-sm-6 {
border: 1px #2e6da4 solid;
padding: 15px 15px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-sm-6 col-xs-12">
</div>
<div class="col-md-4 col-sm-6 col-xs-12">
<canvas id="canvas"></canvas>
</div>
<div class="col-md-4 col-sm-6 col-xs-12">
</div>
</div>
</div>