Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
Making a dynamically resizable Canvas according to the image drawn in it

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);
        }
    }
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!