I am trying to make a dynamically resizable canvas whose width and height can be changed depending on the Image I am trying to load in it and also scaling it down. I have been able to achieve resizable Canvas according to the image width and height, but The Image loads first and then the canvas width and height changes thus Image becomes stretched.
How can I make it so that the canvas resizes first and then the image loads?
let newLowerImgWidth, newLowerImgHeight;
var lower_canvas = document.getElementById('lower-canvas');
function loadImg(){
var ctx = lower_canvas.getContext('2d')
, lower_img = new Image()
, f = document.getElementById("lower_image").files[0]
, url = window.URL || window.webkitURL
, src = url.createObjectURL(f);
lower_img.src = src;
lower_img.onload = () => {
ctx.clearRect(0, 0, lower_canvas.width, lower_canvas.height);
// Scalling down the image
newLowerImgWidth = Math.round(lower_img.width * 0.2);
newLowerImgHeight = Math.round(lower_img.height * 0.2);
// trying to apply width and height to canvas width and height
lower_canvas.style.width = newLowerImgWidth+"px";
lower_canvas.style.height = newLowerImgHeight+"px";
ctx.drawImage(lower_img, 0, 0, newLowerImgWidth, newLowerImgHeight);
url.revokeObjectURL(src);
}
}