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;
    }
}

};

Asd20752
  • 111
  • 1
  • 9

2 Answers2

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.

Sebastian Nette
  • 5,878
  • 2
  • 15
  • 17
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

Community
  • 1
  • 1
dsh
  • 11,380
  • 3
  • 27
  • 48