在尝试为canvas对象创建一个鼠标监听器时,我遇到了一个问题,这个问题花了我很长时间才解决 - 如何将对象变量(this.X,this.Y)传递给事件监听器,例如: / p>
function Test() {
this.canvas = ....
this.mouseDownHandler = ....
canvas.addEventLIstener('mousedown', this.mouseDownListener, false);
}
所以我提出了以下解决方案
答案 0 :(得分:1)
这是为我工作的解决方案 -
function Test() {
this.ctx = this.canvas.getContext("2d");
var self = this;
this.canvas.addEventListener("mousedown",
function(e, param) {
self.mouseDownHandler(e, param);
}.bind(null, this), false);
}
Test.prototype.mouseDownHandler = function(t, e) {
t.ctx.fillRect(e.pageX, e.pageY, 10, 10);
};
答案 1 :(得分:0)
如果您不介意我,可以简单地简化@Yehonatan的答案:
class Test {
constructor() {
this.canvas = document.getElementById("app")
this.ctx = this.canvas.getContext("2d")
this.canvas.addEventListener("mousedown", e => this.mouseDownHandler(e))
}
mouseDownHandler(e) {
this.ctx.fillRect(e.pageX, e.pageY, 10, 10)
}
}
let t = new Test()