如何获取 canvas 内的光标坐标

How to get coordinates of cursor inside canvas

function getPoint ( id ){

    this.point = null

    document. getElementById( id ).addEventListener( 'mousemove', function(i) {
        this.point = i.clientX - i.target.getBoundingClientRect().left    
        console.log( 'this is' + this.point)
    } , false )

}

test = new getPoint ( 'testID' )

setInterval( function(){console.log( 'instance is' + test.point)}, 100 )

我想从 canvasID 创建实例并获取 canvas 内的光标坐标。在这种情况下,console.log 说 'instance is undefined this is 123' 但我无法理解为什么 test.point 是 'undefined',因为我认为 'this.point' 与 'test.point' 相同。

请告诉我如何将“.addEventListener”添加到实例动态。

希望语法错误少一些。

this 在您的事件处理程序回调中将与 getPoint 中的 this 不同;相反,它将是对该元素的引用。

您可以使用变量来记住 this 是什么,然后在处理程序中使用它(请参阅下面的 self):

function getPoint ( id ){
    var self = this;

    self.point = null

    document. getElementById( id ).addEventListener( 'mousemove', function(i) {
        self.point = i.clientX - i.target.getBoundingClientRect().left    
        console.log( 'this is' + self.point)
    } , false )

}

有关 this 的更多信息,请访问我的博客:You must remember this