1

Is there anyway to select a particular instantiated object of a HTML5 Canvas ("this" pointer) after a mouse click from inside that particular canvas? Keep in mind that "Canvas" method I have shown is a non-standard function that I made up.

function Canvas(element) {
    this.canvas = document.createElement("canvas");
    this.context = this.canvas.getContext('2d');
    this.canvas.id = "display";
    var style = {"width" : "500",
                "height" : "500"};
    for(var index in style) {
        this.canvas[index] = style[index];
    }
    element == undefined ? document.body.appendChild(this.canvas) : element.appendChild(this.canvas);
    this.canvas.addEventListener("click", this.click, false);
}

then in a prototyped function I have...

Canvas.prototype.click = function(e) {
        this.mouse = [e.clientX, e.clientY];
        return this.of(this.mouse);
    }

Error: this.of(this.mouse) doesn't exist however I have a prototype for this function (later on) in my code.

0

2 Answers 2

1

The problem is the way you set the onclick handler:

this.canvas.addEventListener("click", this.click, false);
                                      ^^^^^^^^^^

When you add an event listener, you pass the reference, in memory, of the handler. The context of that function (this pointer) is not bounded. So the this pointer in your case will be the canvas element. That's why you've got the following error:

Object #< HTMLCanvasElement > has no method 'of'

To solve the problem you can use the bind function, introduced in Javascript 1.8.5, to bind the context. (Function.prototype.bind reference)

this.canvas.addEventListener("click", this.click.bind(this), false);

See DEMO.

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

1 Comment

Yeah, Canvas.prototype.click(e){} binds to the original instantiated this object and also calls the click function with e.clientX & e.clientY. Thanks.
0

Just a suggestion, but try moving the definition for of() before that of click(). The order of functions is not always significant in JS, but I think it may be for prototypes. I may be wrong (I haven't checked) but it will only take a moment to test.

1 Comment

It didn't change anything.

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.