How To Make A HTML5 Canvas Fit Dynamic Parent/flex Box Container
Is there a way I can create a canvas inside a dynamic re-sizing flex-box container? Preferably a CSS only solution but I think JavaScript is required for redraw? I think one solut
Solution 1:
The only CSS solution I can think about is the use of object-fit:none
(related: How does object-fit work with canvas element?)
$(document).ready(function() {
var ctx = $("#stage")[0].getContext("2d");
ctx.strokeStyle = "#FFFFFF";
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.stroke();
});
html,
body {
margin: 0;
width: 100%;
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
header {
width: 100%;
height: 40px;
background-color: red;
}
main {
display: flex;
flex: 1 1 auto;
border: 1px solid blue;
width: 80vw;
}
canvas {
flex: 1 1 auto;
background-color: black;
object-fit:none;
object-position:top left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
</header>
<main>
<canvas id="stage"></canvas>
</main>
Solution 2:
One other solution is to create a new containing block, and make it follow the formatting context:
const Canvase = styled.canvas`
flex: auto;
position: relative;
left: 0;
top: 0;
width: 100%;
height: 100%;
`;
It is somewhat complimentary/orthogonal to the object-fit: ...
suggested by Temani and Peter
Post a Comment for "How To Make A HTML5 Canvas Fit Dynamic Parent/flex Box Container"