HTML5 Canvas事件监听器和JavaScript - addEventListener(“click”)

时间:2013-06-09 18:23:34

标签: javascript html5-canvas closures addeventlistener

在从特定画布内部单击鼠标后,是否有选择HTML5 Canvas(“this”指针)的特定实例化对象?请记住,我所展示的“Canvas”方法是我编写的非标准功能。

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

然后在原型函数中我有......

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

错误: this.of(this.mouse)不存在但是我的代码中有这个函数的原型(稍后)。

2 个答案:

答案 0 :(得分:1)

问题在于您设置onclick处理程序的方式:

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

添加事件侦听器时,将传递处理程序在内存中的引用。该函数的上下文( this 指针)不受限制。所以你的情况中的 this 指针将是canvas元素。这就是您遇到以下错误的原因:

  

对象#< HTMLCanvasElement>没有方法'of'

要解决此问题,您可以使用Javascript 1.8.5中引入的bind函数来绑定上下文。 (Function.prototype.bind reference)

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

请参阅DEMO

答案 1 :(得分:0)

只是一个建议,但尝试在click()之前移动()的定义。函数的顺序在JS中并不总是很重要,但我认为它可能适用于原型。我可能错了(我没有检查过)但是只需要一点时间来测试。

相关问题