Simplest way to plot points randomly inside a circle

前端 未结 3 1620
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 11:20

I have a basic JSFiddle whereby I want to have random points plotted inside a circle.

But I do not know how to limit the points to be inside the circle.

This is

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 11:35

    To plot points randomly in a circle, you can pick a random value from the radius squared, then square root it, pick a random angle, and convert the polar coordinate to rectangular. The square / square root step ensures that we get a uniform distribution (otherwise most points would be near the center of the circle).

    So the formula to plot a random point in the circle is the following, where r' is a random value between 0 and r2, and θ is a random value between 0 and :

    Screenshot of result:

    Live Demo:

    var canvas = document.getElementById("thecanvas");
    
    var ctx = canvas.getContext('2d'),
        count = 1000, // number of random  points
        cx = 150,
        cy = 150,
        radius = 148;
    
    ctx.fillStyle = '#CCCCCC';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#000000';
    
    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.arc(canvas.width / 2, canvas.height / 2, radius, 0, 2 * Math.PI);
    ctx.closePath();
    
    ctx.fill();
    
    // create random points
    ctx.fillStyle = '#ffffff';
    
    while (count) {
        var pt_angle = Math.random() * 2 * Math.PI;
        var pt_radius_sq = Math.random() * radius * radius;
        var pt_x = Math.sqrt(pt_radius_sq) * Math.cos(pt_angle);
        var pt_y = Math.sqrt(pt_radius_sq) * Math.sin(pt_angle);
        ctx.fillRect(pt_x + canvas.width / 2, pt_y + canvas.width / 2, 2, 2);
        count--;
    }

    JSFiddle Version: https://jsfiddle.net/qc735bqw/

提交回复
热议问题