【问题标题】:Catching the clicks on an HTML5-canvas捕捉 HTML5 画布上的点击
【发布时间】:2017-03-17 01:40:12
【问题描述】:

我想在我的 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')

这段代码有什么问题?

【问题讨论】:

    标签: html coffeescript


    【解决方案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}"
    

    是的,它有效。

    【讨论】:

    • 这也可以使用范围绑定来解决。只需将 -> 替换为 => 即可获得 set 功能。这会将this 上下文从对象传递给函数,而不是让它由函数设置给事件目标。还 +1 用于在找到解决方案后回答您的问题,而不是让它保持打开状态
    猜你喜欢
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2015-01-06
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多