javascript - 使用 php 创建的图像上的鼠标 onclick() 事件

标签 javascript php jquery php-gd

我使用 PHP 代码创建了一个图像,其中代码中的 x 和 y 值解释图像上的点。我想在该图像上执行鼠标单击事件,以便对该图像添加一个点的任何单击都应存储在数据库中。是否可以?如果可能我应该使用哪种方法?你能描述一下吗?

这是我的 php 图像创建代码:

<?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');

?>

这里 $a[$i],$b[$i] 是存储有要在图像上创建的点的 X 和 Y 坐标的数组,并存储在数据库中。因此,包含“ag_fetching.php”文件是为了这个目的。

使用上面的代码,我创建了一个背景颜色为黑色的图像,并在其上点为红色。我可以通过鼠标单击添加点,以便将点记录在所需的数据库中吗?

最佳答案

您可以捕获 JavaScript 中单击事件触发时鼠标所在的像素。这会让您走上正轨吗?

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);
        });

编辑添加了更多代码

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();
        }

关于javascript - 使用 php 创建的图像上的鼠标 onclick() 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41289159/

相关文章:

javascript - Bootstrap datepicker 触发器更改

php - Codeigniter count_all_results 然后得到返回错误号 1066

jquery - jquery悬停问题并单击切换

javascript - 收到 JSON 后,将按钮添加到 html 模板

javascript - 支持拖放的 Html 文件上传文件

javascript - 在热敏打印机上进入 ESC/POS 模式

Javascript 在 Photoshop 中隐藏提示

JavaScript 原型(prototype)编程

php - cakephp 单元类 * 缺失

php mySql 更新集将小数向下舍入