2010-12-02 6 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 반환 화면에 마우스 위치를 고장, 당신은 pageX 자세한 내용은 quirksmode 참조 clientX 또는 IE에서 사용해야합니다.

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.으로 실패합니다. Image()이 새로운 인스턴스를 반환한다는 것을 보장하지 않는다면, 이미지를 생성 할 때 new 키워드를 사용해야합니다.

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

여기서 DOM 오류가 발생하지 않습니다 (FF 3.6). clientX와 screenX의 차이점은 무엇입니까? 나는 기사를 읽을 것이다, 고마워. – thomas

+0

크롬에서 오류가 발생하지만 함수를 호출하면 새 이미지가 반환된다는 보장이 없습니다. 차이점은'screenX'는 화면 왼쪽 상단에서 시작한다는 것입니다. 'clientX'는 웹 페이지의 왼쪽 상단에서 시작합니다. 즉,이 경우에는 후자 만 올바른 결과를 줄 것입니다. –

+0

웹 페이지와 화면의 차이점을 얻지 못했습니다. 나는 그 기사를 읽을 것이다. 고맙습니다. – thomas