2016-11-03 5 views
2

のクリックを私のHTML5のキャンバスにキャッチしたいと思います。HTML5キャンバスのクリックをキャッチする

マイオブジェクト

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') 

何このコードは間違っていますか?

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 

は、このキーワードを使用しないでください。

答えて

1

だから、私は答えを持っています。

  • マウス .position.x
  • マウス .position.y

と::より良い適切なオブジェクト名を使用

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

をええ、それが動作します。

+0

これは、スコープバインディングを使用して解決することもできます。単に、 'set'関数の' - > 'を' => 'に置き換えてください。これは、関数によってイベントターゲットに設定されるのではなく、オブジェクトから関数に 'this'コンテキストを渡します。解決策を見つけた後にあなたの質問に答えても+1してください。 –

関連する問題