I know how to draw rectangles in PHP (with GD), but how do we make them interactive ? I mean, is there a way to be notified when and where the user clicks ?
Eventually, I would like to enable the user to select a rectangle among a set by clicking on it, and clicking anywhere else to move it.
Thanks aforehand.
Regards,
Mister Mystère.
You can do this with image maps. This applies however you create the image. The basic syntax (from Wikipedia) is:
<img src="bild.jpg" alt="alternative text" usemap="#mapname" />
<map name="mapname">
<area shape="rect" coords="9,372,66,397" href="http://en.wikipedia.org/" />
</map>
You can have any number of area
elements. You can either use a regular href URL as shown above, or use JavaScript events. All the typical mouse events are supported (onclick, onmouseover, onmouseout, onmousedown, onmouseup, etc.)
If you only have simple rectangles, an alternative without maps is to just position several images contiguously with no margin or padding.
An input type="image" will give you the coordinates clicked on the image, but that's about it in 'plain' HTML & server-sided PHP.
HTML:
<input type="image" name="myimage" src="whatever.png">
PHP:
$x = $_POST['myimage_x'];
$y = $_POST['myimage_y'];
For more interaction, you'll have to look at javascript, and for even more possibilities I heartily recommend Raphael as a cross-browser (VML for I.E, SVG for the rest) tool capable of more complex images & events on (parts of) that image.
A rectangle in GD is an image like the following example:
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);
// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);
// Save the image
imagepng($im, 'imagefilledrectangle.png');
imagedestroy($im);
To make it interactive you can use CSS like placing the image as a background for a anchor tag:
<a href="#" id="myRectangle"></a>
then in CSS (assuming 2 images):
a#myRectangle{
background-image: url(imagefilledrectangle1.png);
}
a#myRectangle:hover{
background-image: url(imagefilledrectangle2.png);
}
You can do allot more with CSS or take a look at http://jquery.com/ to use JavaScript
For what you are describing, you might consider instead using the HTML5 canvas capabilities. That is, instead of creating a static image using GD in PHP, create the image on the fly using Javascript in the browser. Then you can offer the full range of interactivity and react to mouse movement, clicks.
Take a look at this painting application for an example: http://mugtug.com/sketchpad/
This will, though, require your users have a browser that supports Canvas (firefox, chrome), or for IE, to use something like "explorercanvas". IE9 when it comes out will support canvas I believe, so that should remove that problem.