Simplest way to plot points randomly inside a circle

前端 未结 3 1579
伪装坚强ぢ
伪装坚强ぢ 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--;
    }
    <canvas id="thecanvas" width="400" height="400"></canvas>

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

    0 讨论(0)
  • 2021-02-06 11:46

    JSFiddle

    var ctx = canvas.getContext('2d'),
        count = 1000, // number of random  points
        cx = canvas.width/2,
        cy = canvas.height/2,
        radius = 148;
    
        ctx.beginPath();
        ctx.moveTo(cx, cy);
        ctx.arc(0+canvas.width/2, 0+canvas.height/2, radius, 0, 2*Math.PI);
        ctx.closePath();
        ctx.fillStyle = '#00000';
        ctx.fill();
    
        ctx.fillStyle = '#ffffff';
    
    while(count) {
        var x = Math.random() * canvas.width;
        var y = Math.random() * canvas.height;
        var xDiff = cx - x;
        var yDiff = cy - y;
        if(Math.sqrt(xDiff*xDiff+yDiff*yDiff)<radius)
        {
            ctx.fillRect(x, y, 2, 2);
            count--;
        }    
    }
    
    0 讨论(0)
  • 2021-02-06 11:56

    Randomly pick dSquared (0..radius^2) and theta (0..2pi), then

    x = sqrt(dSquared) cos(theta)
    y = sqrt(dSquared) sin(theta)
    
    0 讨论(0)
提交回复
热议问题