In PHP, the imagefilledpolygon function is used to draw a filled polygon, typically for generating graphics, creating dynamic charts, or creating simple shapes. The most critical point for using this function correctly is the format of the "coordinate array." This article will explain in detail the correct way to write the coordinate array and the key considerations.
bool imagefilledpolygon(
resource $image,
array $points,
int $num_points,
int $color
)
Parameter Explanation:
The most important point: The coordinate array must be a one-dimensional array, arranged in the order x1, y1, x2, y2, x3, y3..., where each pair of elements represents the coordinates of a vertex.
Example:
$points = [
50, 50, // First vertex (x1, y1)
150, 50, // Second vertex (x2, y2)
100, 150 // Third vertex (x3, y3)
];
$num_points = 3;
Then call the function:
imagefilledpolygon($image, $points, $num_points, $color);
Key Considerations:
$image = imagecreatetruecolor(200, 200);
$white = imagecolorallocate($image, 255, 255, 255);
$blue = imagecolorallocate($image, 0, 0, 255);
<p>// Fill background<br>
imagefill($image, 0, 0, $white);</p>
<p>// Define the triangle vertices<br>
$points = [50, 50, 150, 50, 100, 150];<br>
$num_points = 3;</p>
<p>// Draw the filled polygon<br>
imagefilledpolygon($image, $points, $num_points, $blue);</p>
<p>// Output the image<br>
header("Content-Type: image/png");<br>
imagepng($image);<br>
imagedestroy($image);<br>
Running the above code will generate a blue-filled triangle.
When using imagefilledpolygon(), the coordinate array must be a one-dimensional array, with the vertices arranged in the x, y order. $num_points corresponds to the number of vertices, not the length of the array. By mastering this format, you can successfully draw any polygon.