現在の位置: ホーム> 最新記事一覧> ImageOpenPolygon()を使用して、星や雪片などの複雑なグラフィックを描画します

ImageOpenPolygon()を使用して、星や雪片などの複雑なグラフィックを描画します

M66 2025-06-05

PHPでは、 ImageOpenPolygon()は非常に興味深い機能であり、一連の座標ポイントを介して開いた(閉じていない)ポリゴンを描画できます。これは、星やスノーフレークパターンなどの複雑なグラフィックを描く必要がある場合に特に便利です。

この記事では、ImageOpenPolygon()を使用する方法を例で説明し、シンプルな5点の星と基本的なスノーフレーク構造を描く方法を示します。

基本的な理解:ImageOpenPolygon()関数

bool imageopenpolygon(
    GdImage $image,
    array $points,
    int $num_points,
    int $color
)
  • $画像:描画する画像リソース。

  • $ポイント[x1、y1、x2、y2、...]の形式のすべての頂点座標を含む配列。

  • $ num_points :頂点の数。

  • $色:線の色。

注: ImageOpenPolygon()はこれらのポイントを順番に接続しますが、図を自動的に閉じません。

例1:5点の星を描きます

まず、キャンバスを作成し、シンプルな5点の星を描きます。

 <?php
// キャンバスを作成します
$image = imagecreatetruecolor(300, 300);

// 色を割り当てます
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白い背景
$starColor = imagecolorallocate($image, 255, 0, 0); // 赤い星

// 背景を埋めます
imagefill($image, 0, 0, $backgroundColor);

// 5つの尖った星の頂点を定義します
$points = [
    150, 20,   // トップ
    179, 110,
    270, 110,
    197, 165,
    220, 250,
    150, 200,
    80, 250,
    103, 165,
    30, 110,
    121, 110
];

// 開いた五gramを描きます
imageopenpolygon($image, $points, count($points) / 2, $starColor);

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

// 画像リソースを破壊します
imagedestroy($image);
?>

star.phpとして保存した後、次のようなブラウザにアクセスしてください。

 https://m66.net/star.php

描かれた5点の星を見ることができます。

例2:基本的なスノーフレークパターンを描きます

単純なスノーフレークは、中央の対称放射線でシミュレートできます。

 <?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()は、オープンタイプのグラフィックを描くための強力なツールです。数学的な計算(三角関数など)と組み合わせることで、星、雪片、さらに複雑な芸術的パターンなど、さまざまな興味深い複雑なグラフィックを作成できます。

Cooler Complexグラフィックを生成する場合は、ループロジックと調整アルゴリズムを組み合わせて、この描画機能をさらに拡張することを検討できます。