I am facing a challenge with a canvas element inside a div:
<div class="preview"><canvas id="cropped" width="2480" height="2003"></canvas></div>
The div block is smaller than the canvas. How can I make the canvas autofit in two different scenarios:
- Automatically adjust canvas width proportionally to parent div's width
- Automatically adjust canvas height proportionally to parent div's height
I have attempted the following approach:
public autofit = (orientation: RegistryOrientation) => {
let previews = document.getElementsByClassName('preview');
if (previews.length > 0) {
let preview = previews[0];
let width = preview.clientWidth;
let height = preview.clientHeight;
if (orientation === RegistryOrientation.album) {
this.imgCanvas.style.width = width + 'px';
this.imgCanvas.style.height = 'auto';
} else if (orientation === RegistryOrientation.book) {
this.imgCanvas.style.height = height + 'px';
this.imgCanvas.style.width = 'auto';
}
}
};