Canvas How to - Test if click inside a circle








Question

We would like to know how to test if click inside a circle.

Answer


<!--  w w w.j  av a 2 s  .  com-->

<!DOCTYPE html>
<html>
<head>

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var offsetX = canvas.offsetLeft;
        var offsetY = canvas.offsetTop;
        var cx = canvas.width / 2;
        var cy = canvas.height / 2;
        var r = 20;
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
        ctx.closePath();
        ctx.stroke();
        function handleEvent(e) {
            var evt = e ? e : window.event;
            clickX = evt.clientX - offsetX;
            clickY = evt.clientY - offsetY;
            var dx = cx - clickX;
            var dy = cy - clickY;
            if (dx * dx + dy * dy <= r * r) {
                alert("you are inside the circle");
            }
            return false;
        }
        canvas.addEventListener("click", handleEvent);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="400px" height="400px"></canvas>
</body>
</html>

The code above is rendered as follows: