2012-10-11 3 views
1

안녕하세요, 저는 자바 스크립트에 초보자이고, 드림위버 편집기에 HTML5 캔버스를 사용하고 있습니다. 마우스 이벤트에 관한 다른 게시물을 살펴 봤지만 아무도 내 문제를 해결하지 못하는 것 같습니다.html5에서 이미지를 클릭하기위한 마우스 이벤트 만들기

나는 옥수수 거품을 클릭하기 위해 마우스를 움직이지만 게임을 끝내면 다른 곳을 클릭하면 '옥수수 거품을 클릭하십시오'라는 게임을 만듭니다. 지금까지 내가 사용한

: 그들은 해당 있도록

window.addEventListener("keydown",eventKeyDown,false); 
window.addEventListener("keyup",eventKeyUp,false); 
window.addEventListener("mousedown",onDown,false); 
window.addEventListener("mouseup",onUp,false); 
window.addEventListener("mousemove",onMove,false); 

어떻게 내가이 전화를 할

? 또한 어떻게하면 클릭 할 수있게되어 이미지가 떨어지는 것처럼 클릭 할 수있게됩니다.

+0

대부분의 사람들은 클릭 이벤트가 발생 '고 앉았다을 볼 때 요소에 사용자가 클릭. click 이벤트는 mousedown 및 mouseup 이벤트 후에 발생합니다. https://developer.mozilla.org/en-US/docs/DOM/element.onclick –

답변

2

이것이 도움이 될 수 있습니다.

document.addEventListener('click',mouseClick,false); 
function mouseClick(e) 
{ 
    mouseX = e.pageX - canvas.offsetLeft; 
    mouseY = e.pageY - canvas.offsetTop; 
    //Now mouseX and mouseY contains the x and y location of mouse click event but w.r.t. your canvas location . 
} 
+0

건배! 나는 내가이 방법을 더 잘 이해한다고 생각한다. –

+0

이것이 도움이되었다고 기쁘다. 그것이 도움이된다면, pls. 대답을 당신의 받아 들인 대답으로 표시하십시오. :) – Vijay

+0

확실 :) 어떻게 잘 모르겠지만? 난 그냥 새 회원으로 시작 –

0

우선 마우스 커서가 어디에 있는지 찾아야합니다. 여기에 마우스 좌표를 얻을 수있는 기능입니다 : 예 마우스와 이미지의 좌표를 찾을 경우

function getMousePosition(e) { 
    var x, y;   

    x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - canvas.offsetLeft; 
    y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop - canvas.offsetTop; 

    return { 
     get x() { return x }, 
     get y() { return y } 
    } 
} 

HTMLCanvasElement.prototype.getMousePosition = getMousePosition; 

그런 다음 우리가 마우스를 클릭 한 경우 테스트해야합니다. 마우스 좌표가 이미지 좌표와 겹치는 경우에는 무언가를하십시오. 우리는 다음과 같은 방법 같은 조건을 테스트 할 수 있습니다

var isMouseDown = false; 
function onDown(e) { 
    var pos = {x:0, y:0 }; 
    isMouseDown = true; 
    var mouseCoordinate = getMousePosition(e); 
    for (var i = 0; i < images.length; i++) { 
     var bubble = images[i]; 
     if ((mouseCoordinate.x > image.x && // get the image most left position 
      mouseCoordinate.x < image.x + image.size) && // get image most right position 
      (mouseCoordinate.y > image.y && 
       mouseCoordinate.y < image.y + image.size)) { 
      index = image.indexOf(image, 0); 
      pos.x = mouseCoordinate.x; 
      pos.y = mouseCoordinate.y; 
      break; 
     } 
    } 
} 


if (isMouseDown && 
    pos.x < image[index].x + image[index].size && 
    pos.x > image[index].x && 
    pos.y < image[index].y + image[index].size && 
    pos.y > image[index].y) 
// if the condition is true, then do something   

function onUp(e) { 
    isMouseDown = false; 
} 

당신이있어 라이브 예를 볼 수 있습니다 http://hellopixel.net/experiments/404/404.html

+0

@esimov 감사합니다! 내 튜터가 제안한 바로 그게 전부 다 등록하는 법을 모르겠다. 이 코드를 HTML의 특정 위치에 넣을 수 있습니까? –