I am striving to create an HTML/CSS layout that utilizes flexbox to fill available space with various elements, while also maximizing the size of a 2D canvas within that space.
Although CSS flexbox can help achieve this desired layout, there is a challenge when it comes to resizing the canvas element. The canvas backing store needs to be redrawn in order to prevent distortion, such as stretching a low-resolution image too far or compressing a high-resolution image and losing details.
The provided code snippet (available on jsfiddle) comes close to achieving the intended goal. However, the canvas does not update its size dynamically when CSS3 animations are applied.
HTML:
<button>I am a button</button>
<canvas id="c"></canvas>
<p>Some text.</p>
CSS:
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-direction: column;
}
canvas {
flex: auto;
align-self: stretch;
}
button {
align-self: center;
transition: padding 2s;
}
button:hover {
padding: 3em;
}
Javascript:
function redraw() {
var cc = c.getContext("2d");
c.width = c.clientWidth;
c.height = c.clientHeight;
cc.scale(c.width, c.height);
cc.beginPath();
cc.arc(0.5, 0.5, .5, 0, 2 * Math.PI);
cc.fill();
}
// Update canvas on window resize.
window.addEventListener("resize", redraw);
// Initial drawing of the canvas.
redraw();