PHP uses GD library to generate line chart

As shown in the figure, the PHPGD library generates a line chart;

Here I only talk about the principles. As for optimizing the interface and encapsulating data methods, you can split and optimize them yourself.

<?php 
// 1.创建画布
$width = 600;
$height= 400;
$image=imagecreatetruecolor($width,$height);


$red = imagecolorallocate($image, 45, 56, 12);
$fff = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$red);

// x轴
imageline($image,0,399,599,399,$fff);
// y轴
imageline($image,0,399,0,0,$fff);

//X轴单位
for($i=0;$i<10;$i++){
	$num = $i * 6 *10;
	imageline($image,$num,399,$num,395,$fff);
}
//y轴单位
for($i=0;$i<10;$i++){
	$num = $height -($i * 4 *10);
	imageline($image,0,$num,5,$num,$fff);
}
// 描点
for($i=0;$i<10;$i++){
	if($i > 0){
		$prenum = $num ;
		$preynum = $ynum ;
	}
	$num = $i * 6 *10;
	$ynum = rand(0,$height);
    imagesetpixel($image, $num , $ynum ,$fff);
	// 设置值
	$str = (string)($height - $ynum);
	if($ynum < $preynum){
		imagestring($image,4,$num,$ynum-20,$str,$fff);
	}else{
		imagestring($image,4,$num,$ynum+20,$str,$fff);

	}
	// imagechar($im, 5, 0, 0, $string, $black);
	// 连线
	// var_dump($str);
	if($i > 0){
		imageline($image,$prenum,$preynum,$num,$ynum,$fff);
	}
	
}

// imageline($image,rand(0,500),rand(0,300),rand(0,500),rand(0,300),create_color($image));

// 4.输出或保存
header('content-type:image/jpg');
imagejpeg($image);


imagedestroy($image);

 

Guess you like

Origin blog.csdn.net/wqzbxh/article/details/106786564