Current Location: Home> Latest Articles> What is the correct format for the coordinate array in the imagefilledpolygon function? Detailed explanation here

What is the correct format for the coordinate array in the imagefilledpolygon function? Detailed explanation here

gitbox 2025-09-12

What is the correct format for the coordinate array in the imagefilledpolygon function? Detailed explanation here

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.

Function Prototype

bool imagefilledpolygon(
    resource $image,
    array $points,
    int $num_points,
    int $color
)

Parameter Explanation:

Correct Format of the Coordinate Array

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:

  1. The array must be one-dimensional. Do not use a two-dimensional array to represent the vertices, as it will cause an error.
  2. $num_points must equal the number of vertices, not the number of array elements. Remember, each pair of elements represents one vertex.
  3. The coordinates can be integers or floating-point numbers, but integers are typically used to represent pixel positions.
  4. The order of the vertices in the array will affect the shape of the polygon. It is recommended to arrange them in a clockwise or counterclockwise order.

Complete Example

$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.

Summary

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.