Question

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();
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top