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

152
Visualizações
JS drawImage as a method in class

I started a simple project in javascript a few days ago and found this issue. Every time I reload my google-page i get an empty canvas. I have already tried to take out the drawImage() function out of class and it worked. But what if I need to use that function as a class method? (Also I've already tried passing the canvas as an argument of the draw method but it doesn't work)

So this is working but I don't need it

const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')

var img = new Image()
img.src = 'some source'
ctx.drawImage(img,10,10)

And this isn't working but supposed to

const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')

class Person
{
  constructor(name){
    this.name = name
    this.img = new Image()
    this.img.src = 'some source'
  }
  draw(){
    ctx.drawImage(this.img,10,10)
  }
}

var peter = new Person('Peter Griffin')
peter.draw()
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The reason is simple. Your image is not loaded when you want to draw it.

You have to wait until the image is loaded before drawing it in the canvas.

const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')

class Person
{
    constructor(name){
        this.name = name;
        this.img = new Image()
        this.img.src = 'monimage.jpg'
    }
    on_image_loaded(f) {
        this.img.onload = f;
    }
    draw(){
        ctx.drawImage(this.img,10,10)
    }
}

var peter = new Person('Peter Griffin')
peter.on_image_loaded(function() {
    peter.draw();
});

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