In my application I have a div with a canvas element inside it that display an image. The application also has a sidebar that can be hidden by clicking a button, and all the other elements should resize themselves to take the empty remaining space.
This works well for divs and other elements that have a width/height set to percents, but not for the canvas element.
This is the div I have:
<div id="background-img" class="image-div"></div>
.image-div {
height: inherit;
width: 100%;
margin-top: 25px;
position: absolute;
}
where the height is initially 305px but it changes to 375px when the sidebar is hidden.
This is the canvas creation code:
const imgDiv = document.getElementById('background-img');
if (imgDiv) {
const blob = new Blob([svg], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const canvas = document.createElement('canvas');
canvas.className = 'canvas-background';
canvas.id = 'canvas-id';
const ctx = canvas.getContext('2d');
canvas.width = imgDiv.clientWidth;
canvas.height = imgDiv.clientHeight;
const img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = url;
imgDiv.appendChild(canvas);
}
and the canvas has no additional css defined anywhere.
How can I make it possible for the canvas to resize itself as soon as the parent changes his width and height (I am trying to make this resize work also when I zoom in/out the page like you do it in chrome for example, something that works with divs or img elements).
canvas { width: 100% }, then perhaps also a resize listener if you want to also update the canvas's internal pixel width (rather than display width which is determined by the CSS) - DBS