1

I'm trying to write a javascript class for an area that contains 2 canvas elements, 1 for background and 1 for foreground. But when i click on canvas i get the error:

"Uncaught TypeError: Cannot read property 'drawImage' of undefined"

Any help would be appreciated...

function GAMEAREA(canvasElement, bgElement)
{
    this.canvas = document.getElementById(canvasElement);
    this.context = this.canvas.getContext("2d");
    this.bgCanvas = document.getElementById(bgElement);
    this.bgContext = this.bgCanvas.getContext("2d");
    this.pawnImg = document.getElementById("pawnImg");

    this.init = function()
    {
        this.adjustSize();
        this.canvas.addEventListener("mousedown", this.onClick, false);
    };

    this.onClick = function(e)
    {
        this.context.drawImage(this.pawnImg, 0, 0);
    };

    this.adjustSize = function()
    {
        this.canvas.height = window.innerHeight - ($("#headerDiv").outerHeight() +     $("#footerDiv").outerHeight());
        if (this.canvas.height > window.innerWidth) {
            this.canvas.height = window.innerWidth;
            this.canvas.width = this.canvas.height;
        }
        else this.canvas.width = this.canvas.height;
        this.bgCanvas.height = this.canvas.height;
        this.bgCanvas.width = this.canvas.width;
        this.bgCanvas.style.display = "block";
        this.canvas.style.display = "block";
    };

    this.init();
}
ion
  • 79
  • 2
  • 9
  • 1
    [Here's a great related question](http://stackoverflow.com/questions/3127429/javascript-this-keyword) that explains how `this` works in JavaScript. – voithos Apr 24 '14 at 23:19

2 Answers2

4

The problem is that this isn't what you think it is in your click handler, which means that this.context is undefined and undefined doesn't have a drawImage() method. Try using the .bind() method:

this.canvas.addEventListener("mousedown", this.onClick.bind(this), false);

...to force this to the value you need. Or you can do something like this:

function GAMEAREA(canvasElement, bgElement)
{
    var self = this;
    ...    
    this.onClick = function(e)
    {
        self.context.drawImage(self.pawnImg, 0, 0);
    };    
    ...
}

The value of this within a function depends on how that function is called. More information about how this is set is available at MDN.

nnnnnn
  • 138,378
  • 23
  • 180
  • 229
-3

You're problem lies in these lines:

this.canvas = document.getElementById(canvasElement);
this.context = this.canvas.getContext("2d");

this.context is undefined. Make sure that the above lines are returning the correct objects.

Justin C
  • 313
  • 1
  • 7
  • Yes i know that, but i cannot understand why it is undefined. I think the canvas is accessed ok, because it is resized properly. – ion Apr 24 '14 at 23:22