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

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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