Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda