如何在画布内获取光标的坐标

How to get coordinates of cursor inside canvas

本文关键字:光标 坐标 获取 布内      更新时间:2023-09-26
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 )

我想从画布ID创建实例并获取该画布内的光标坐标。在这种情况下,控制台.log说"实例未定义,这是 123",但我不明白为什么 test.point 是"未定义的",因为我认为"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在我的博客上:你必须记住this