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

134
Visualizações
I Can't draw an image using drawImage method in html5 canvas

I am trying to create dino cloud game. but I encouter a problem .When I try to draw the image of the dinosaur in the canvas using drawImage method , the image is not drawn . Can you help me please.

const canvas = document.querySelector(".canvas");
canvas.height = 400;
canvas.width = 800;

const ctx = canvas.getContext("2d");

class Dino {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = (88 * this.height) / 94;
    this.height = 70;
  }
  draw() {
    let image = new Image();
    image.src = "imgs/player/idle/dino-idle-1.png";
    ctx.drawImage(image, this.x, this.y, this.width, this.height);
  }}
  
const dino = new Dino(20, 200);
dino.draw();

I tried to draw dino using window.onload but it is not working

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to draw an image on canvas only after the image is fully loaded (For example, using the onload trigger on the image).

Example below:

const canvas = document.querySelector(".canvas");
canvas.height = 400;
canvas.width = 800;

const ctx = canvas.getContext("2d");

class Dino {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.height = 70;
    this.width = (88 * this.height) / 94;
  }
  draw() {
    const image = new Image();
    image.onload = () => ctx.drawImage(image, this.x, this.y, this.width, this.height);
    image.src = "https://www.fillmurray.com/600/400";
  }}
  
const dino = new Dino(20, 200);
dino.draw();
<canvas class="canvas"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório
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