I am currently in the process of creating a dashboard using the Bootstrap grid. Some of the cells contain a canvas
element, and I am trying to ensure that it matches the size of its parent. My approach involves the following calculations:
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;
}
Despite implementing this, the canvas, or the cell, seems to keep increasing in height when I resize the page, and I am puzzled by this behavior.
For a demonstration, run the following example in full page and resize the window horizontally to see how the cells continue to grow 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>