I am working with an application that includes a div containing a canvas element to display an image. Additionally, there is a sidebar that can be hidden with the click of a button, causing all other elements to resize and adjust to the remaining space.
While this resizing behavior works well for elements with width/height set as percentages, it does not seem to apply to the canvas element itself.
The div structure I currently have is as follows:
<div id="background-img" class="image-div"></div>
.image-div {
height: inherit;
width: 100%;
margin-top: 25px;
position: absolute;
}
The initial height of the div is 305px but changes to 375px when the sidebar is hidden.
Below is the code used to create the canvas:
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);
}
No additional CSS styles are applied to the canvas elsewhere in the code.
I'm seeking a way to enable the canvas to automatically resize itself whenever its parent's width and height change. This should include functionality for zooming in/out on the page, similar to how it behaves on Chrome with divs or img elements. Any guidance on achieving this would be greatly appreciated.