X-Axis runs horizontally at the center for the image for which Y = 100.
We will declare some variables.
$width=800; // Width of the Image Canvas
$height=200; // Height of the canvas
$steps=2; // The Jump in value of X - Axis for each loop.
Step: In the script the amount of movement of X axis in each loop. You can see we draw line between two coordinates and the value of 2nd coordinate is taken from the first.
$x2=$x1+ $steps
Note that this value of the $step determines the sharpness of the curves. Higher the value of step less will be the sharpness. Similarly with less number of steps more looping is required so sharpness of the curve increases.
No of loops required.
To draw the curve we will use the loop and the loop will take one upper limit which is taken from this formula.
for($i=1;$i<=($width/$steps);$i++){
As we start from left edge ( X=0 ) so number of steps required is total width divided by steps taken in each loop.
How the curve is drawn
We used one for loop to draw lines between two coordinates. To draw this line we will use imageline function which takes two coordinates to draw line between them.
On next iteration of the loop, the 1st coordinate takes the values of 2nd coordinate of previous iteration of the loop.
For example in one loop the first coordinate is x1=20,y1=25 . Our 2nd Coordinate is x2=23,y2=27. IN the next loop we will have x1=23,y1=27, so the line will start from where we left at previous loop.
$x1=$x2;
We know that sin value varies between -1 and +1. SIN(90) = 1 and SIN(270)=-1.
So our curve will reach its peak at SIN(90) which should be within our top of the image. So we will use one multiplier to adjust the height of the curve.
Our sin() function takes input in radian so we used deg2rad() function to convert degree value to radian. The math function number_format() is used to remove the decimal places. We have used 90 as multiplier factor here to scale the curve. If we use this value as 100 the top edge of the curve will match with top edge of the image. We kept it 90 to keep some gap.
DEMO of SIN curve using PHP GD →
The complete code is here.
<?Php
header("Content-type: image/jpg");
$width=800; // Width of the Image Canvas
$height=200; // Height of the canvas
$steps=2; // The Jump in value of X - Axis for each loop.
$x1=0;
$im = @ImageCreate ($width, $height)
or die ("Cannot Initialize new GD image stream");
$background_color = ImageColorAllocate ($im, 244, 244, 244); // Assign background color
$text_color = ImageColorAllocate ($im, 51, 51, 255); // text color is given
imageline ( $im , 0 , $height/2 , $width , $height/2 , 245 ); // X axis
for($i=1;$i<=($width/$steps);$i++){
$y1=($height/2)-number_format(sin(deg2rad($x1))*90,0);
$x2=$x1+$steps;
$y2=($height/2)-number_format(sin(deg2rad($x2))*90,0);
imageline ( $im , $x1 , $y1 , $x2 , $y2 , $text_color );
$x1=$x2;
}
ImagePng ($im); // image displayed
?>
Drawing COS curve
In your editor just search and replace sin with cos. Your cos curve is ready.