Canvas How to - Click inside a circle








Question

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

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<!--   w w w .ja  va  2  s.  com-->
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var dc = $("canvas")[0].getContext("2d");
    dc.beginPath();
    dc.arc(50, 50, 10, 0, Math.PI*2, false);
    dc.closePath();
    dc.strokeStyle = "red";
    dc.stroke();

    dc.beginPath();
    dc.arc(55, 55, 10, 0, Math.PI*2, false);
    dc.closePath();
    dc.strokeStyle = "blue";
    dc.stroke();
    function intersects(x, y, cx, cy, r) {
        var dx = x-cx;
        var dy = y-cy;
        return dx*dx+dy*dy <= r*r;
    }
    console.clear();
    $("canvas").on("click", function (e){
        if (intersects(e.pageX, e.pageY, 55, 55, 10))
            console.info(e.pageX + ", " + e.pageY );
    });
});//]]>  
</script>
</head>
<body>
  <canvas width="400" heigth="300" />
</body>
</html>

The code above is rendered as follows: