Reputation: 172
I'm trying to draw circles at random positions in a PHP generated picture, starting from the center point of image and contained in a "N" pixels radius.
I know how to do it in square boundaries (and i would quite know how to do it in a diamond shape too), but the circular way to do it is a bit more difficult to comprehend for me.
Here is the code i've got so far. The image is 600*600px, i generate 100 white circles of 25*25px in a 300*300px square area horizontally and vertically centered.
$w = $h = 600;
$img = imagecreatetruecolor($w,$h);
$cl = imagecolorallocatealpha($img,255,255,255,0);
for ($i=0;$i<=100;$i++){ // GENERATE 100 CIRCLES
$x = rand(150,450);
$y = rand(150,450);
imagefilledellipse($img, $x, $y, 25, 25, $cl);
}
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);
What would be the best way to generate these circles in circular boundaries ?
So that, for instance, if $x=155 it could not be at $y=155, or if $x=445 it could not be $y=445
Thanks for help !
EDIT This is the new code with polar coordinates
$w = $h = 600;
$img = imagecreatetruecolor($w,$h);
$cl = imagecolorallocatealpha($img,255,255,255,0);
for ($i=0;$i<=100;$i++){ // GENERATE 100 CIRCLES
$r = rand(25,(300-25));
$a = rand(0,360);
$x = $r * cos(deg2rad($a));
$y = $r * sin(deg2rad($a));
imagefilledellipse($img, $x, $y, 25, 25, $cl);
}
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);
Upvotes: 1
Views: 237
Reputation: 2438
Instead of trying to find the (x,y) coordinates, you can randomize the polar coordinates:
And then convert these polar coordinates via the standard formulas
x = r * cos(t)
y = r * sin(t)
Upvotes: 1