Simplest way to plot points randomly inside a circle

前端 未结 3 1610
伪装坚强ぢ
伪装坚强ぢ 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: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)

提交回复
热议问题