Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

416
Vistas
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();
   };
 };
};
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda