2010-12-02 58 views
0

我想知道用戶是否點擊畫布中繪製的圖片。我點擊圖片,但沒有任何反應。該警報未被調用。最後一個條件永遠不會通過。任何想法?畫布元素:圖片點擊

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
    <body> 
     <div id="wrapper"> 
      <canvas id="game" height="500" width="700"> 
      </canvas> 
     </div> 
     <script> 
     (function() { 
      var canvas = document.getElementById('game'), 
       context = canvas.getContext('2d'), 
       fps = 1, 
       character = Image(), 
       positions = [[125, 55], [480, 55], [125, 185], [480, 182], [125, 315], [480, 315]], 
       random, x, y, xc, yc = null; 

      canvas.addEventListener('click', function(event) { 
       xc = event.screenX - canvas.offsetLeft; 
       yc = event.screenY - canvas.offsetTop; 

       if((xc >= x) && (xc <= (x + character.width)) && (yc >= y) && (yc <= (y + character.height))) { 
        alert('X = ' + x + 'Y = ' + y); 
       } 
      }, true); 

      character.src = 'character.png'; 

      setInterval(function() { 
       random = (Math.floor(Math.random() * 6)); 

       random = positions[random]; 
       x = random[0]; 
       y = random[1]; 

       context.clearRect(0, 0, canvas.width, canvas.height); 
       context.drawImage(character, x, y); 
      }, 1000/fps); 
     }()); 
     </script> 
    </body> 
</html> 

回答

2

這裏有兩個問題。

首先,你的事件代碼被打破相對於屏幕鼠標位置screenX回報,你需要使用clientX或IE pageX看到quirksmode以獲取更多信息。

canvas.addEventListener('click', function(event) { 
    event = event || window.event; // IE does not pass the event param! 

    // you should use var infront of these local variables 
    // otherwise you leak them into the global namespace 
    // and you can even overwrite things there if you don't watch out 
    var xc = (event.clientX ? event.clientX : pageX) - canvas.offsetLeft; 
    var yc = (event.clientY ? event.clientY : pageY) - canvas.offsetTop; 

其次,代碼從未在Chrome中運行!它在第15行失敗,因爲Uncaught TypeError: DOM object constructor cannot be called as a function.。您在創建映像時需要使用new關鍵字,因爲否則不能保證Image()將返回新實例。

... 
context = canvas.getContext('2d'), 
fps = 1, 
character = new Image(), 
... 
+0

DOM錯誤在這裏沒有發生(FF 3.6)。 clientX和screenX有什麼區別?我會閱讀文章,謝謝。 – thomas 2010-12-02 19:15:10