Estoy tratando de hacer un lienzo de tamaño variable dinámicamente cuyo ancho y alto se pueden cambiar según la imagen que estoy tratando de cargar en él y también reducirlo. He podido lograr un lienzo redimensionable de acuerdo con el ancho y el alto de la imagen, pero la imagen se carga primero y luego el ancho y el alto del lienzo cambian, por lo que la imagen se estira.
¿Cómo puedo hacer que el lienzo cambie de tamaño primero y luego se cargue la imagen?
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); } }