javascripthtml5-canvasdrawimage

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()

Solution

  • 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();
    });