我想抓住 HTML5-canvas 上的点击次数。
我的对象:
mouse =
position:
x: 0
y: 0
set: (event) ->
boundaries = canvas.getBoundingClientRect()
this.position.x = event.clientX - boundaries.left
this.position.y = event.clientY - boundaries.top
我的事件监听器:
window.addEventListener 'click', (event) ->
event.preventDefault()
mouse.position.set event
console.log "#{mouse.position.x} - #{mouse.position.y}"
错误消息:
TypeError: undefined is not an object (evaluating 'this.position.x = event.clientX - boundaries.left')
这段代码有什么问题?
答案 0 :(得分:1)
所以,我有答案:
mouse =
position:
x: 0
y: 0
set: (event) ->
boundaries = canvas.getBoundingClientRect()
mouse.position.x = event.clientX - boundaries.left
mouse.position.y = event.clientY - boundaries.top
您不应该使用this关键字。更好地使用正确的对象名称:
和
canvas.addEventListener 'click', (event) ->
event.preventDefault()
mouse.position.set event
console.log "#{mouse.position.x} - #{mouse.position.y}"
是的,它有效。