본문 바로가기

web

HTML5 마우스 다운 이벤트 - context.isPointInPath()로 체크



function addEvent(config) {
    var event = window.event;
    var canvas = config.canvas;
    var context = config.context;
    var left = config.left;
    var top = config.top;
    var size = config.size;
     
    canvas.addEventListener("mousedown", function(event){     
          var canvasPos = getCanvasPos(canvas);
          var mouseX = event.clientX - canvasPos.left + window.pageXOffset;
          var mouseY = event.clientY - canvasPos.top + window.pageYOffset;      
          var right = left + size;
          var bottom = top + size;
          var isDownInRect = false;

          context.clearRect(0, 0, canvas.width, canvas.height);
          context.beginPath();               
          context.fillStyle = "#EF8BEF";
          context.rect(left, top, size, size);
          context.fill();

          if(context.isPointInPath(mouseX, mouseY)) {
               isDownInRect = true;
          }

          context.clearRect(0, 0, 300, 60);
          context.font = "12pt Calibri";
          context.fillStyle = "black";
          context.fillText("down position :::  x : " + mouseX + " y : " + mouseY, 10, 15);
          context.fillText("is down in rect : " + isDownInRect, 10, 30);
     }, false);
}

function drawRect() {     
     var canvas = document.getElementById("drawER1Canvas");
     var context = canvas.getContext("2d");     
     var size = 100;
     var left = (canvas.width - size) * 0.5;
     var top = (canvas.height - size) * 0.5;
     context.clearRect(0, 0, canvas.width, canvas.height);
     context.beginPath();               
     context.fillStyle = "#EF8BEF";
     context.rect(left, top, size, size);
     context.fill();  

     context.font = "12pt Calibri";
     context.fillStyle = "black";
     context.fillText("down position :::  none", 10, 15);
     context.fillText("is down in rect : false", 10, 30);         

     return {
          canvas: canvas,
          context: context,
          size: size,
          left: left,
          top: top
     }
}  

function getCanvasPos(canvas) {
     var obj = canvas;
     var top = 0;
     var left = 0;
     while (obj.tagName != "BODY")
     {
          top += obj.offsetTop;
          left += obj.offsetLeft;
          obj = obj.offsetParent;
     }

     return {
          top: top,
          left: left
     };
}

 

<head>에서 메서드들 정의하고 <body>에서 addEvent(drawRect()); 실행.

 

마우스 다운 이벤트가 발생할 때 canvas를 모두 지우고 다시 그린다. 사각형을 다시 그릴때, context.isPointInPath(mouseX, mouseY) 이거로 현재 다운된 마우스 좌표가 그리고 있는 패스상에 있는지를 체크한다.