0

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);
        }
    }
Mandeep Singh
  • 83
  • 1
  • 10
  • 1
    Use `width/height` properties of the canvas instead of inline styles. – Teemu May 23 '22 at 08:57
  • I am already using it but the main problem is that image loads before the canvas resizes, thus the image gets stretched. `lower_canvas.style.width = newLowerImgWidth+"px"; lower_canvas.style.height = newLowerImgHeight+"px";` – Mandeep Singh May 23 '22 at 09:08
  • 1
    The stretching doesn't happen because of canvas resizing when using `width/height` properties, rather the dimensions you're calculating are incorrect. Use `naturalWidth/height` of the image and the aspect ratio to calculate the dimensions of the image, then scale them to fit your needs. See [an example](https://stackoverflow.com/a/53525555/1169519) of resizing an image (done in `resizeImage` function). – Teemu May 23 '22 at 09:12
  • 1
    You're using inline styles, (`lower_canvas.style.width`), use `lower_canvas.width` instead. `width/height` properties of a canvas define the dimensions of the graphics area in pixels, when you set `style.width/height`, the pixels count is not changed, the existing pixels are only stretched to fit the element's size. – Teemu May 23 '22 at 09:29
  • That solved it, Thanks for helping me out. – Mandeep Singh May 23 '22 at 09:59

0 Answers0