PHP用GD库模拟时钟

PHP图像处理虽有更好的ImageMagick,但GD库仍有很多用户。本文给出用GD库模拟时钟的小例子,根据系统时间只做了秒针,主要涉及三角函数弧度计算,通过1秒刷新一次网页实现,包含clock.html和clock.php两个文件,前者用js调用后者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php 图像处理现在有更好的ImageMagick。但GD库还是用户颇多。小例子模拟时钟。
根据系统时间,只做了秒针。主要是三角函数弧度计算。然后1秒刷新一次网页即可。
两个文件:

clock.html

<body>
	<img id="clock" src="clock.php">
	<script>
		setInterval(function(){
			document.getElementById("clock").src="clock.php?"+Math.random();
		},1000);
	</script>
</body>

用js调用clock.php,1秒刷新一次。

clock.php

<?php
	//获取系统时间
	$h = date("H");
	$i = date("i");
	$s = date("s");

	//1 创建资源(画布的大小)
	$img = imagecreatetruecolor(200, 250);
	//设置画布的颜色
	$white = imagecolorallocate($img,0xFF,0xFF,0xFF);
	$red = imagecolorallocate($img,255,0,0);
	$blue = imagecolorallocate($img,0,0,0xFF);
	$green = imagecolorallocate($img,0,0xFF,0);
	
	imagefill($img,0,0,$white);

	//2.制作颜色
	imageellipse($img, 100, 100, 190,190, $blue);
	imageellipse($img, 100, 100, 4,4, $blue);
	
	//2.画图
	imagestring($img, 3, 95, 8, "12", $blue);
	imagestring($img, 3, 180, 95, "03", $blue);
	imagestring($img, 3, 95, 180, "06", $blue);
	imagestring($img, 3, 11, 95, "09", $blue);

	//秒针 2PI = 360
	$len = 80;
	$a = $len*sin(pi()/180*6*$s);
	$b = $len*cos(pi()/180*6*$s);
	$x = 100 + $a;
	$y = 100 - $b;

	imageline($img, 100, 100, $x, $y, $red);

	//数字时间
	imagestring($img, 5, 40, 230, "NOW: {$h}:{$i}:{$s}", $red);
	
	//4.保存,或者输出给浏览器 (写第二个参数,保存)	
	header("Content-Type:images/gif");
	imagegif($img);

	//5.释放资源
	imagedestroy($img);
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值