在PHP 中, imagefilledarc是一個非常實用的函數,常用於繪製帶填充色的扇形或者弧形。借助它,我們可以輕鬆實現弧形進度條的繪製效果。如果能將這個進度條做成交互式的動態展示,用戶體驗會更好,視覺效果也更為炫酷。
本文將詳細講解如何使用imagefilledarc來製作一個交互式弧形進度條,並實現動態進度的視覺效果。
imagefilledarc函數的語法如下:
imagefilledarc(
resource $image,
int $cx,
int $cy,
int $width,
int $height,
int $start,
int $end,
int $color,
int $style
): bool
$image :畫布資源。
$cx , $cy :圓弧中心點坐標。
$width , $height :圓弧橢圓的寬和高。
$start , $end :起始角度和結束角度(單位為度,0度指向3點鐘方向,逆時針方向為正)。
$color :填充顏色。
$style :繪製風格,一般用IMG_ARC_PIE來畫扇形。
以下代碼示例畫出一個弧形進度條,假設進度為75%。
<?php
header("Content-Type: image/png");
$width = 200;
$height = 200;
$image = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($image, 255, 255, 255);
$bar_color = imagecolorallocate($image, 50, 150, 250);
$gray_color = imagecolorallocate($image, 230, 230, 230);
imagefill($image, 0, 0, $bg_color);
// 畫灰色底部圓弧,代表總進度
imagefilledarc($image, $width/2, $height/2, 150, 150, 0, 360, $gray_color, IMG_ARC_PIE);
// 動態進度 75%
$progress = 75;
$end_angle = ($progress / 100) * 360;
// 畫彩色進度圓弧
imagefilledarc($image, $width/2, $height/2, 150, 150, 0, $end_angle, $bar_color, IMG_ARC_PIE);
imagepng($image);
imagedestroy($image);
?>
PHP 是服務器端語言,不能直接控制客戶端的交互和動態變化。但我們可以通過參數傳遞的方式,讓用戶輸入或前端傳進度值,然後重新請求PHP 腳本,輸出對應進度的圖片。
例如,前端頁面通過AJAX 或表單傳入進度參數:
http://m66.net/progress.php?value=60
PHP 腳本接收value參數,然後生成對應進度條。
<?php
// progress.php
$value = isset($_GET['value']) ? intval($_GET['value']) : 0;
if ($value < 0) $value = 0;
if ($value > 100) $value = 100;
header("Content-Type: image/png");
$width = 200;
$height = 200;
$image = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($image, 255, 255, 255);
$bar_color = imagecolorallocate($image, 50, 150, 250);
$gray_color = imagecolorallocate($image, 230, 230, 230);
imagefill($image, 0, 0, $bg_color);
imagefilledarc($image, $width/2, $height/2, 150, 150, 0, 360, $gray_color, IMG_ARC_PIE);
$end_angle = ($value / 100) * 360;
imagefilledarc($image, $width/2, $height/2, 150, 150, 0, $end_angle, $bar_color, IMG_ARC_PIE);
imagepng($image);
imagedestroy($image);
?>
然後在HTML 裡,利用JavaScript 定時刷新圖片,形成動態進度條效果:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>交互式弧形進度條演示</title>
</head>
<body>
<img id="arcProgress" src="http://m66.net/progress.php?value=0" alt="進度條" />
<br/>
<button onclick="startProgress()">開始進度</button>
<script>
let progress = 0;
let timer;
function startProgress() {
if (timer) clearInterval(timer);
progress = 0;
timer = setInterval(() => {
if (progress > 100) {
clearInterval(timer);
return;
}
document.getElementById('arcProgress').src = `http://m66.net/progress.php?value=${progress}&t=${Date.now()}`;
progress += 2;
}, 100);
}
</script>
</body>
</html>
增加中心文字:使用imagestring或imagettftext在進度條中央顯示百分比數字。
多色漸變:結合多個弧形分段繪製,營造漸變效果。
圓環樣式:畫兩個弧形,一個作底環,一個作進度環,中間留白形成圓環。
前端Canvas :用PHP 生成數據,前端用Canvas 實現更流暢動畫。
通過本文介紹的方法,結合imagefilledarc的繪製功能與簡單的參數交互,可以輕鬆做出功能實用且視覺效果良好的交互式弧形進度條,適合用於後台報表、任務進度提示等場景。
希望你能用這個思路做出炫酷的進度條!祝你編碼愉快!