JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrapper">
<div class="divA"></div>
<div class="divB">
<canvas id="canvas"></canvas>
</div>
<div class="divC"></div>
</div>
CSS
* {
box-sizing: border-box;
}
body {
height: 100vh;
margin: 0;
}
.wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
height: 100%;
}
.wrapper div {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
border: 1px solid;
}
.wrapper .divB {
border: none;
}
#canvas {
vertical-align:top;
}
JavaScript
var canvas = document.getElementById("canvas");
var WIDTH = 500; // This could be anything! it comes from
//previous calculations which I did not include here because they are irelevant
document.getElementsByClassName('divB')[0].style.flex = '0 0 ' + WIDTH + 'px';
var width = document.getElementsByClassName('divB')[0].getBoundingClientRect().width;
var height = document.getElementsByClassName('divB')[0].getBoundingClientRect().height;
document.getElementById("canvas").style.width = width + 'px';
document.getElementById("canvas").style.height = height + 'px';
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, width, height);
// resize handler Ref: https://developer.mozilla.org/en-US/docs/Web/Events/resize
(function() {
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function resizeThrottler() {
if (!resizeTimeout) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
}, 66);
}
}
function actualResizeHandler() {
var width = document.getElementsByClassName('divB')[0].getBoundingClientRect().width;
var height = document.getElementsByClassName('divB')[0].getBoundingClientRect().height;
document.getElementById("canvas").style.width = width + 'px';
document.getElementById("canvas").style.height = height + 'px';
ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, width, height);
}
}());