萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 庫繪製 3D 立體圓餅圖完整實作

效果展示

3D Pie Chart Demo

核心類別:Pie3D

<?php
class Pie3D {
    const ANGLE_STEP = 5; // 繪圖精度:角度步進

    private $img;
    private $width, $height;
    private $centerX, $centerY;
    private $radiusX, $radiusY; // 橢圓半徑 (3D 效果)
    private $height3D;          // 3D 厚度
    private $colors = [];       // 色盤
    private $data = [];         // [{label, value, color}, ...]
    private $total = 0;

    public function __construct($width = 500, $height = 350, $height3D = 30) {
        $this->width = $width; $this->height = $height; $this->height3D = $height3D;
        $this->img = imagecreatetruecolor($width, $height);
        // 背景白色
        $white = imagecolorallocate($this->img, 255, 255, 255);
        imagefill($this->img, 0, 0, $white);
        // 中心點與橢圓半徑
        $this->centerX = $width / 2;
        $this->centerY = $height / 2 + $height3D / 2; // 向下偏移留空間給側面
        $this->radiusX = min($width, $height - $height3D) * 0.4;
        $this->radiusY = $this->radiusX * 0.5; // 橢圓扁平比例
        // 預設色盤
        $this->colors = [
            [255, 99, 132], [54, 162, 235], [255, 206, 86],
            [75, 192, 192], [153, 102, 255], [255, 159, 64],
            [199, 199, 199], [83, 102, 255], [255, 99, 255],
        ];
    }

    public function addData($label, $value, $color = null) {
        $this->data[] = ['label' => $label, 'value' => (float)$value, 'color' => $color];
        $this->total += $value;
    }

    private function allocateColor($rgb) {
        return imagecolorallocate($this->img, $rgb[0], $rgb[1], $rgb[2]);
    }

    private function darkenColor($rgb) {
        return [$rgb[0] / 2, $rgb[1] / 2, $rgb[2] / 2];
    }

    private function ellipsePoint($angleDeg) {
        $rad = deg2rad($angleDeg);
        return [
            round($this->centerX + $this->radiusX * cos($rad)),
            round($this->centerY + $this->radiusY * sin($rad))
        ];
    }

    // 繪製單一切片 (含頂面、側面、邊緣)
    private function drawSlice($startDeg, $endDeg, $rgb, $darkRgb, $isTop = true) {
        $colorTop = $this->allocateColor($rgb);
        $colorSide = $this->allocateColor($darkRgb);
        $colorEdge = $this->allocateColor([max(0, $rgb[0]-40), max(0, $rgb[1]-40), max(0, $rgb[2]-40)]);

        // 頂面扇形
        if ($isTop) {
            imagefilledarc($this->img, $this->centerX, $this->centerY, $this->radiusX*2, $this->radiusY*2,
                $startDeg, $endDeg, $colorTop, IMG_ARC_PIE | IMG_ARC_NOFILL); // 先畫邊緣
            imagefilledarc($this->img, $this->centerX, $this->centerY, $this->radiusX*2, $this->radiusY*2,
                $startDeg, $endDeg, $colorTop, IMG_ARC_PIE); // 填滿
        }

        // 3D 側面:由多個矩形條構成
        $steps = max(1, (int)(($endDeg - $startDeg) / self::ANGLE_STEP));
        for ($i = 0; $i <= $steps; $i++) {
            $deg = $startDeg + ($endDeg - $startDeg) * $i / $steps;
            [$x1, $y1] = $this->ellipsePoint($deg);
            [$x2, $y2] = $this->ellipsePoint($deg + 0.5); // 微小角度差形成三角條
            // 側面多邊形:頂面邊緣 -> 底面邊緣
            $poly = [
                $x1, $y1,
                $x2, $y2,
                $x2, $y2 + $this->height3D,
                $x1, $y1 + $this->height3D
            ];
            imagefilledpolygon($this->img, $poly, 4, $colorSide);
            // 邊緣線
            imageline($this->img, $x1, $y1 + $this->height3D, $x2, $y2 + $this->height3D, $colorEdge);
        }
        // 兩側垂直面
        [$sx1, $sy1] = $this->ellipsePoint($startDeg);
        [$ex1, $ey1] = $this->ellipsePoint($endDeg);
        $polyStart = [$sx1, $sy1, $ex1, $ey1, $ex1, $ey1 + $this->height3D, $sx1, $sy1 + $this->height3D];
        imagefilledpolygon($this->img, $polyStart, 4, $colorSide);
    }

    public function render() {
        // 先畫所有側面 (從後往前),再畫頂面
        $currentDeg = -90; // 從 12 點鐘方向開始
        foreach ($this->data as $i => $item) {
            $sliceDeg = 360 * $item['value'] / $this->total;
            $rgb = $item['color'] ?? $this->colors[$i % count($this->colors)];
            $dark = $this->darkenColor($rgb);
            $this->drawSlice($currentDeg, $currentDeg + $sliceDeg, $rgb, $dark, false); // 只畫側面
            $currentDeg += $sliceDeg;
        }
        // 重新畫頂面 (覆蓋側面上緣)
        $currentDeg = -90;
        foreach ($this->data as $i => $item) {
            $sliceDeg = 360 * $item['value'] / $this->total;
            $rgb = $item['color'] ?? $this->colors[$i % count($this->colors)];
            $dark = $this->darkenColor($rgb);
            $this->drawSlice($currentDeg, $currentDeg + $sliceDeg, $rgb, $dark, true);
            $currentDeg += $sliceDeg;
        }
    }

    public function output($type = 'png') {
        header('Content-Type: image/' . $type);
        $func = 'image' . $type;
        $func($this->img);
        imagedestroy($this->img);
    }
}
?>

使用範例

<?php
require_once 'Pie3D.php';

$chart = new Pie3D(600, 400, 35);
$chart->addData('Chrome', 65, [66, 133, 244]);
$chart->addData('Safari', 18, [255, 187, 0]);
$chart->addData('Firefox', 8, [255, 70, 0]);
$chart->addData('Edge', 5, [0, 170, 210]);
$chart->addData('Other', 4, [180, 180, 180]);
$chart->render();
$chart->output('png');
?>

關鍵算法解析

  1. 橢圓參數方程:x = cx + rx·cosθ, y = cy + ry·sinθ 計算邊緣座標。
  2. 3D 側面建模:將扇形側面切割為多個梯形條,利用 imagefilledpolygon 繪製,模擬立體厚度。
  3. 繪製順序:先繪所有側面 (避免遮擋),再繪頂面扇形覆蓋上緣,最後可疊加圖例。
  4. 顏色深淺:側面顏色 = 頂面顏色 × 0.5,邊緣再暗 40,產生光影層次。

擴充建議

  • 加入圖例 (Legend) 繪製區域,使用 imagettftext 輸出中文標籤。
  • 支援「突出顯示」某一切片 (Offset 位移)。
  • 輸出 SVG 格式以利向量縮放與互動。
  • 整合 pChart、SVGGraph 等成熟庫替代手繪,生產環境更穩健。
copyright © 萬盛學電腦網 all rights reserved