• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

262
Views
How Can the HTML Canvas Be Full Height, but Maintain Aspect Ratio with Its Background Image?

I want an html canvas to have a background image and I want my drawing on that background image to maintain its location when I resize the image. I also want the canvas to take up the entire screen. I can keep the canvas drawing in line with the background image when the canvas's height is the same as the background image's calculated height. But when the canvas is full screen size, resizing the canvas smushes the drawing, and it doesn't stay in line with the background image.

canvas doesn't line up with background image when canvas.style.height is 100% enter image description here

canvas does stay in line with the background image, but the canvas is not full size enter image description here

And here's the code used for the resize event handler:

const onResize = () => {
  let backgroundImageWidth, backgroundImageHeight;
  const backgroundImageSource = document.querySelector("#responsive-canvas")
  .style.backgroundImage;
  const problemBackgroundImage = new Image();
    
  problemBackgroundImage.onload = function () {
   let aspect_ratio = this.width / this.height;
   backgroundImageWidth = 0.45 * window.innerWidth;
   backgroundImageHeight = backgroundImageWidth / aspect_ratio;
    
   const calculatedHeight = window.innerWidth / aspect_ratio;
    
   let img = document.createElement("img");
   img.src = dataURL; // dataURL is the value of canvas.toDataURL()
    
   canvas.width = window.innerWidth;
   canvas.height = calculatedHeight;
   canvas.style.height = calculatedHeight; // commenting out this line gives me the fullsize canvas, but the drawing does not line up.
    
   img.onload = function () {
     context.drawImage(img, 0, 0, canvas.width, canvas.height);
     context.restore();
   };
 };
};
almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error