我正在尝试更改" selectedArea"的值我从鼠标获得的值。每当我尝试这样做时,我得到" Uncaught TypeError:无法读取属性' start'未定义"。 (鼠标按下()) 可能是一个简单的解决方案,只是我看不到它(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;
}
}
};
答案 0 :(得分:1)
您缺少调用该函数的正确上下文:
canvasSource.addEventListener("mousedown", this.mouseDown.bind(this));
如果你没有绑定上下文,那么监听器内的this
会引用被点击的元素,即画布。
答案 1 :(得分:0)
根据您调用该函数的方式,this
将不是您期望的对象。 this
关键字在Javascript中与其他语言(例如Java,C ++)不同。
https://stackoverflow.com/a/3127440/1172714
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this