Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading