0

I am trying to change the value of "selectedArea" to the values I get from the mouse. Whenever I try to do so I get "Uncaught TypeError: Cannot read property 'start' of undefined". (mouseDown()) Probably an easy solution, just that I can not see it(quite new to javascript).

var areaSelection = {
mouseisDown: false,
selectedArea: {
    start: { x: 0, y: 0 },
    end: { x: 0, y: 0 }
},
initialize: function () {
    canvasSource.addEventListener("mousedown", this.mouseDown);
    canvasSource.addEventListener("mousemove", this.mouseMove);
    canvasSource.addEventListener("mouseup", this.mouseUp);
},
mouseDown: function (event) {
    if (!this.mouseisDown) {
        this.selectedArea.start.x = event.clientX;
        this.selectedArea.start.y = event.clientY;
    }
},
mouseMove: function (event) {
    if (this.mouseisDown) {
        var x = this.selectedArea.start.x;
        var y = this.selectedArea.start.y;
        var width = event.clientX - x;
        var height = event.clientY - y;
        drawOverlay(x, y, width, height);
    }
},
mouseUp: function (event) {
    if (this.mouseisDown) {
        this.selectedArea.end.x = event.clientX;
        this.selectedArea.end.y = event.clientY;
    }
}

};

1
  • We're missing a piece of the puzzle here... Commented Jul 8, 2015 at 19:05

2 Answers 2

1

You are missing the correct context in which the function is called:

canvasSource.addEventListener("mousedown", this.mouseDown.bind(this));

If you don't bind the context then the this inside the listener refers to the clicked element, which is the canvas.

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

Comments

0

Depending on how you call the function, this will not be the object you expected. The this keyword is different in Javascript from other languages (eg Java, C++).

https://stackoverflow.com/a/3127440/1172714

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Comments

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.