當前位置: 首頁> 最新文章列表> 使用imageopenpolygon() 繪製複雜圖形如星形、雪花圖

使用imageopenpolygon() 繪製複雜圖形如星形、雪花圖

M66 2025-06-05

在PHP 中, imageopenpolygon()是一個非常有趣的函數,它允許你通過一組坐標點繪製開口(不封閉)的多邊形。這在需要繪製複雜圖形,例如星形或雪花圖案時特別有用。

本文將通過實例講解如何使用imageopenpolygon() ,並展示如何繪製一個簡單的五角星和一個基礎雪花結構。

基礎了解:imageopenpolygon() 函數

bool imageopenpolygon(
    GdImage $image,
    array $points,
    int $num_points,
    int $color
)
  • $image :要繪製的圖像資源。

  • $points :包含所有頂點坐標的數組,形式為[x1, y1, x2, y2, ...]

  • $num_points :頂點數量。

  • $color :線條的顏色。

注意: imageopenpolygon()會按順序連接這些點,但不會自動閉合圖形。

示例一:繪製一個五角星

首先,我們創建一個畫布並繪製一個簡單的五角星:

 <?php
// 創建畫布
$image = imagecreatetruecolor(300, 300);

// 分配顏色
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$starColor = imagecolorallocate($image, 255, 0, 0); // 紅色星形

// 填充背景
imagefill($image, 0, 0, $backgroundColor);

// 定義五角星頂點
$points = [
    150, 20,   // 頂部
    179, 110,
    270, 110,
    197, 165,
    220, 250,
    150, 200,
    80, 250,
    103, 165,
    30, 110,
    121, 110
];

// 繪製開口五角星
imageopenpolygon($image, $points, count($points) / 2, $starColor);

// 輸出圖像
header('Content-Type: image/png');
imagepng($image);

// 銷毀圖像資源
imagedestroy($image);
?>

保存為star.php後,在瀏覽器訪問,如:

 https://m66.net/star.php

即可看到繪製出來的五角星。

示例二:繪製一個基礎雪花圖案

一個簡單的雪花可以通過中心對稱的放射線條來模擬:

 <?php
$image = imagecreatetruecolor(300, 300);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
$snowColor = imagecolorallocate($image, 0, 0, 255);

imagefill($image, 0, 0, $backgroundColor);

// 雪花中心
$centerX = 150;
$centerY = 150;
$length = 100;
$arms = 6;

// 計算各個點
$points = [];
for ($i = 0; $i < $arms; $i++) {
    $angle = deg2rad(360 / $arms * $i);
    $x = $centerX + cos($angle) * $length;
    $y = $centerY + sin($angle) * $length;
    $points[] = $centerX;
    $points[] = $centerY;
    $points[] = $x;
    $points[] = $y;
}

// 繪製雪花
imageopenpolygon($image, $points, count($points) / 2, $snowColor);

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

保存為snowflake.php後,在瀏覽器訪問:

 https://m66.net/snowflake.php

就能看到一個放射狀的基礎雪花結構了!

小結

imageopenpolygon()是繪製開放式圖形的利器,結合數學計算(比如三角函數),你可以創建各種有趣複雜的圖形,比如星星、雪花、甚至更加複雜的藝術圖案。

如果你想生成更炫酷的複雜圖形,可以考慮結合循環邏輯和坐標算法,進一步擴展這種繪製能力!