Canvas How to - Get random points on circle








Question

We would like to know how to get random points on circle.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from w  w w  .j  a  va 2  s  .  c o  m-->
function line(ax, ay, bx, by) {
    ctx.beginPath();
    ctx.moveTo(ax, ay);
    ctx.lineTo(bx, by);
    ctx.stroke();
}
function randomPoint() {
    var angle = Math.random() * Math.PI * 2;
    var x = c + r * Math.sin(angle);
    var y = c + r * Math.cos(angle);
    return {x: x, y: y};
}
function distance(p1, p2) {
    return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
var c = 200,
    r = 190;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var points = 0;
while ( points < 20 ) {
    var p1 = randomPoint(),
        p2 = randomPoint();
    var d = distance(p1, p2);
    if ( d >= 1.5 * r ) {
        points++;
        line(p1.x, p1.y, p2.x, p2.y);
    }
}
}//]]>  
</script>
</head>
<body>
  <canvas width=400 height=400 id=canvas></canvas>
</body>
</html>

The code above is rendered as follows: