In PHP, if you want to draw a regular polygon, such as a pentagon, hexagon or more, we can use the ** trigonometric function (sin and cos) to easily calculate the coordinates of each vertex and draw it through the imageopenpolygon() function.
This tutorial will explain in detail how to implement it.
First, make sure your PHP environment has the GD graphics library enabled. GD is the basic library for drawing images. If you are using a regular PHP server, it is usually enabled by default.
A trigonometric function can convert an angle to a coordinate point. Suppose we use a certain center point (centerX, centerY) as the reference and fixed the radius radius , the angle of each vertex can be passed:
$angle = 2 * pi() * $i / $sides;
in:
$i is the index of the current point (how many points)
$sides is the number of sides, for example, the pentagon is 5
pi() returns pi π, 2π is a complete circle (360 degrees)
Then, use:
$x = $centerX + $radius * cos($angle);
$y = $centerY + $radius * sin($angle);
Calculate the position of each vertex.
Here is a practical example, generating a regular hexagon (6-sided) and drawing it onto the picture:
<?php
// Create a canvas
$image = imagecreatetruecolor(400, 400);
// Assign colors
$background = imagecolorallocate($image, 255, 255, 255); // White background
$polygonColor = imagecolorallocate($image, 0, 0, 255); // Blue polygon
// Fill the background
imagefill($image, 0, 0, $background);
// Polygon parameters
$sides = 6; // Number of edges
$centerX = 200; // centerX
$centerY = 200; // centerY
$radius = 100; // radius
// Generate vertex
$points = [];
for ($i = 0; $i < $sides; $i++) {
$angle = 2 * pi() * $i / $sides - pi() / 2; // Starting upward,So subtract90Degree
$x = $centerX + $radius * cos($angle);
$y = $centerY + $radius * sin($angle);
$points[] = $x;
$points[] = $y;
}
// Draw open polygons(Will not close automatically)
imageopenpolygon($image, $points, $sides, $polygonColor);
// Output pictures to browser
header('Content-Type: image/png');
imagepng($image);
// Destroy resources
imagedestroy($image);
?>
imageopenpolygon() is an open polygon, the start and end points are not automatically connected. If you need to close the graphics, use imagepolygon() instead.
The coordinate array is arranged in order and the format is [x0, y0, x1, y1, x2, y2, ...] .
Don't forget to destroy the resource imagedestroy($image) at the end, otherwise the memory will leak.
If you want to save the image to the server, for example to https://m66.net/uploads/polygon.png , you can do this:
imagepng($image, '/path/to/uploads/polygon.png');
Remember to make sure the /path/to/uploads/ directory exists and has write permissions in advance!