JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outerContainer">
<canvas></canvas>
<div class="beside">
</div>
</div>
CSS
* {
box-sizing: border-box;
}
body {
margin: 0;
}
.outerContainer {
display: flex;
border: 0.5em solid #444;
margin-bottom: 2em;
/*max available flexbox height*/
height: calc(100vh - 2em);
}
.outerContainer canvas {
background: #77a;
/*max available canvas width*/
width: calc(100vw - 4em);
}
.outerContainer .beside {
flex-basis: 3em;
flex-grow: 0;
flex-shrink: 0;
background: #7a7;
}
JavaScript
// Document.ready
$(() => {
putImageOnCanvas();
});
// Window resize event
((() => {
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function resizeThrottler() {
if (!resizeTimeout) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
}, 66);
}
}
function actualResizeHandler() {
// handle the resize event - reloading page for illustration
window.location.reload();
}
})());
function putImageOnCanvas() {
$('.outerContainer canvas').each((index, canvas) => {
const ctx = canvas.getContext('2d');
canvas.width = $(canvas).innerWidth();
canvas.height = $(canvas).innerHeight();
const img = new Image;
img.src = 'https://static1.squarespace.com/static/56a1d17905caa7ee9f27e273/t/56a1d56617e4f1177a27178d/1453446712144/Picture7.png';
img.onload = (() => {
// find the aspect ratio that fits the container
let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
let centerShift_x = (canvas.width - img.width * ratio) / 2;
let centerShift_y = (canvas.height - img.height * ratio) / 2;
canvas.width -= 2 * centerShift_x;
canvas.height -= 2 * centerShift_y;
// reset the flexbox height and canvas flex-basis (adjusting for the 0.5em border too)
$('.outerContainer').css({
'height': 'calc(' + canvas.height + 'px + 1em)'
});
$('.outerContainer canvas').css({
'width': 'calc(' + canvas.width + 'px)'
});
// draw the image in the canvas now
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width * ratio, img.height * ratio);
});
});
}