Canvas How to - Get mouse cursor distance to circle center








Question

We would like to know how to get mouse cursor distance to circle center.

Answer


<!--   w ww  .  java 2 s .c om-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    $(function () {
        var context = document.getElementById("myCanvas").getContext("2d");
        context.beginPath();
        context.moveTo(250, 250);
        context.arc(250, 250, 200, 0, Math.PI * 2, false);
        context.closePath();
        context.fillStyle = 'rgb(255,100,0)';
        context.fill();
        $("canvas").mousemove(function (e) {
            var x = e.pageX;
            var y = e.pageY;
            var dist = Math.round(Math.sqrt(Math.pow(x - 250.0, 2) + Math.pow(y - 250.0, 2)));
            console.log(dist);
        });
    });
});//]]>  
</script>
</head>
<body>
    <canvas id="myCanvas" width="800" height="800"></canvas>
</body>
</html>

The code above is rendered as follows: