Timo Timo - 28 days ago 14
CoffeeScript Question

Catching the clicks on an HTML5-canvas

I'd like to catch the clicks on my HTML5-canvas.

My object:

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


My event listener:

window.addEventListener 'click', (event) ->
event.preventDefault()
mouse.position.set event
console.log "#{mouse.position.x} - #{mouse.position.y}"


The error message:

TypeError: undefined is not an object (evaluating 'this.position.x = event.clientX - boundaries.left')


What's wrong with this piece of code?

Answer

So, I have the Answer:

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

You should not use the this keyword. Better use the proper object name:

  • mouse.position.x
  • mouse.position.y

and:

canvas.addEventListener 'click', (event) ->
  event.preventDefault()
  mouse.position.set event
  console.log "#{mouse.position.x} - #{mouse.position.y}"

yeah, it works.