I am trying to create a simply function in php that will take some int inputs and use them to draw a rectangle but the below function doesn’t work…
<?php
$img = imagecreatetruecolor(500, 500);
$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
//set canvas background to white
imagefill($img, 0, 0, $white);
//THIS FUNCTION IS NOT WORKING
function draw($x1Pos, $y1Pos, $x2Pos, $y2Pos, $colour) {
imagerectangle($img, $x1Pos, $y1Pos, $x2Pos, $y2Pos, $colour);
}
draw(20, 40, 60, 80, $red);
draw(30, 40, 80, 100, $green);
imagerectangle($img, 150, 100, 300, 250, $green);
imagerectangle($img, 100, 100, 200, 200, $blue);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
Your code is failing for two reasons; firstly,
$imgis never passed to the function. You either need to declare it as global within the function, or pass it through a parameter.Secondly,
$bluedoesn’t exist. Replace that or actually write it into existence, and your code works fine.