Mouse onclick() event on images created by using php

1.1k views Asked by At

I had an image created by using PHP code in which the x and y values in the code interpret the points on the image. I would like to perform mouse click event on that image such that any click on that image who add an point to that and should store in the database. Is it possible? If possible which method should I use? Can you describe?

Here goes my php image creation code:

<?php

include('ag_fetching.php');

header("Content-type: image/png");

$image = imagecreatetruecolor(800, 800);

$red = imagecolorallocate($image, 250, 0, 0);

for($i=0;$i<$count;$i++)

{
imagefilledellipse($image, $a[$i], $b[$i], 10, 10, $red);

}

imagepng($image,'ag_graph.png');

?>

Here $a[$i],$b[$i] are arrays stored with X an Y coordinates of points to be created on image and are stored in database.So ,inclusion of "ag_fetching.php" file is for that purpose.

Using the code above I create an image with background color as black and points on that as red. Can I add points by mouse clicks such that points are to be recorded in a desired database?

2

There are 2 answers

0
Jose Manuel Abarca Rodríguez On

I can do it with three files :

  • coords.php : this is the main page, where image is displayed and the click events are captured.
  • coords_img.php : this file reads the coordinates x,y from database, generates the image with the red spots, and this image is returned to coords.php.
  • coords_db.php : this file receives the x,y coordinate from a click event and store it in database, then it returns to coords.php to refresh the page.

Next three files work like a charm, you just create three files with the same names, copy-paste next codes in the files and open coords.php in your browser :

coords.php

<?php
session_start();
if ( ( ! isset($_SESSION["arr_x"]) ) ||
     ( ! isset($_SESSION["arr_y"]) ) )
   { $_SESSION["arr_x"] = array(10,620,50); // ◄■■ THIS IS OUR "DATABASE"
     $_SESSION["arr_y"] = array(10,45,100); // ◄■■ (FOR TESTING PURPOSES).
   }
?>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type = "text/javascript">
//====================================================
$(function() // ◄■■ CLICK EVENT OF THE IMAGE.
{ $("#my_image").click( function(e)
    { var offset = $(this).offset();
      $("#x").val( parseInt(e.pageX - offset.left) );
      $("#y").val( parseInt(e.pageY - offset.top) );
      $("#frm_xy").submit(); // ◄■■ GO TO "COORDS_DB.PHP".
    } );
} );
//====================================================
    </script>
  </head>
  <body>
    <br/><br/>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <img id="my_image" src="coords_img.php"/> <!--◄■■ IMAGE WITH RED SPOTS-->

    <form style="display:none" action="coords_db.php" <!--◄■■ HIDDEN FORM-->
          method="post" id="frm_xy">
      <input type="text" id="x" name="x"/>
      <input type="text" id="y" name="y"/>
    </form>
  </body>
</html>

coords_img.php

<?php
ob_start();
session_start();
$image = imagecreatetruecolor(800, 600);
$red = imagecolorallocate($image, 250, 0, 0);

$a = $_SESSION["arr_x"]; // ◄■■ READ COORDINATES
$b = $_SESSION["arr_y"]; // ◄■■ FROM DATABASE.
for ( $i=0; $i < count($a); $i++ )
  imagefilledellipse($image, $a[$i], $b[$i], 10, 10, $red);

header( 'Content-type: image/jpeg' );
ob_end_flush(); // ◄■■ I NEED THIS TO MAKE IT WORK,
ob_end_clean(); // ◄■■ WITHOUT IT I GET NO IMAGE.
imagepng( $image );
?>

coords_db.php

<?php
session_start();
if ( isset($_POST["x"]) && isset($_POST["y"]) )
   { array_push( $_SESSION["arr_x"], $_POST["x"] );  // ◄■■ STORE X AND Y
     array_push( $_SESSION["arr_y"], $_POST["y"] );  // ◄■■ IN DATABASE.
   }
header("location: coords.php"); // ◄■■ RETURN TO REFRESH PAGE.
?>

In my example codes I use two $_SESSION variables to simulate the database : $_SESSION["arr_x"] and $_SESSION["arr_y"], they work fine. To make it work with a real database you will have to remove the two $_SESSION variables from the three files, then you add a connection to database and a "insert" query in coords_db.php, finally, you add another connection to database and a "select" query in coords_img.php.

4
nrylee On

You can capture the pixel the mouse was on when the click event fires in JavaScript. Does that put you on the right track?

imageElement.addEventListener('click', function () {
            alert('ClientX: ' + event.clientX
                + '\nClientY: ' + event.clientY
                + '\nPageX: ' + event.pageX
                + '\nPageY: ' + event.pageY
                + '\nScreenX: ' + event.screenX
                + '\nScreenY: ' + event.screenY
                + '\nX: ' + event.X
                + '\nY: ' + event.Y
                + '\nOffsetX: ' + event.offsetX
                + '\nOffsetY: ' + event.offsetY);
        });

EDIT Further Code Added

window.addEventListener('load', function () {
            document.getElementById('--IdOfImage--').addEventListener('click', saveClickData);
        });
        function saveClickData() {
            var xhr = new XMLHttpRequest();
            var image = this;
            var xVal = event.offsetX;
            var yVal = event.offsetY;
            var url = '/path/to/captureClickInfo.php?x=' + xVal + '&y=' + yVal;
            xhr.onreadystatechange = function () {
                if (xhr.readyState==4) {
                    if (xhr.status==200) {
                        // Should probably use this code to refresh image.
                        image.src = '/path/to/image.php'; //Not sure if this works if src doesn't change...
                    }
                    else {
                        // An error occured if reaches here.
                    }
                }
            }
            xhr.open('GET', url);
            xhr.setRequestHeader('Content-type', 'your/data-format');
            xhr.send();
        }