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 what I currently have:
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 150,
cy = 150,
radius = 148;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(canvas.width/2, canvas.height/2, radius, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = '#00000';
ctx.fill();
// create random points
ctx.fillStyle = '#ffffff';
while(count) {
// randomise x:y
ctx.fillRect(x + canvas.width/2, y + canvas.height/2, 2, 2);
count--;
}
How would i go about generating random (x,y) coordinates to plot random points inside the circle?
My current fiddle: http://jsfiddle.net/e8jqdxp3/
r=Math.random()*radius
thenx = cx + r * Math.cos(pt_angle);
andy = cy + r * Math.sin(pt_angle);
and thenfillRect(x,y,2,2)
. Also note that if the full radius is randomly selected, a 2px rect can escape the boundary of the circle because rects are defined with their x,y at top-left. A simple fix is to use (radius-2) or a lengthier fix is to trap that edge case when the angle is between -PI/2 and PI/2. – Pomposity