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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

Yes i know that, but i cannot understand why it is undefined. I think the canvas is accessed ok, because it is resized properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.