捕获HTML5画布上的点击

时间:2016-11-03 12:53:47

标签: html5 coffeescript

我想抓住 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')

这段代码有什么问题?

1 个答案:

答案 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关键字。更好地使用正确的对象名称:

  • 小鼠 .position.x
  • 小鼠 .position.y

canvas.addEventListener 'click', (event) ->
  event.preventDefault()
  mouse.position.set event
  console.log "#{mouse.position.x} - #{mouse.position.y}"
是的,它有效。