mercredi 6 mai 2015

Access Javascript prototype function inside Image.onload

I'm quite new to Javascript and I've been tasked to create a widget for a site we're developing. The problem is that I'm getting an error when trying to call a prototype function from within the onload() event of an Image. I'll now provide a simplified version of the widget:


In our constructor, we dynamically create a canvas element, attach it to the given container, and load the image to be drawn.
function Widget(container_id, size) {

    this.size = size;

    // creating canvas.
    this.canvas = document.createElement("canvas");
    this.canvas.setAttribute("width", this.size);
    this.canvas.setAttribute("height", this.size);

    // adding canvas to DOM.
    var container = document.getElementById(container_id);
    container.appendChild(this.canvas);

    // loading images.
    this.image = new Image();
    this.image.onload = function() {
        this._draw(); // ERROR here.
    }
    this.image.src = "my_image.png";
}

Later we define the drawing function.

Widget.prototype._draw = function() {

    var ctx = this.canvas.getContext("2d");
    ctx.drawImage(this.image, 0, 0, this.size, this.size);
};

And we use it like this:

<htmL>
  ...
  <div id="container"></div>
  ...
  <script>
    var widget = new Widget("container", 50);
  </script>
  ...
</html>


Now, when we load this page in the browser (Firefox 37.0, in this case), we get the following error:
TypeError: this._draw is not a function

What's the issue, and, which is the correct way to accomplish this? Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire