简体   繁体   English

使用Javascript将鼠标单击坐标插入文本输入框

[英]Insert Mouse Click Coordinates into text input box with Javascript

I have an HTML5 Canvas on my page along with two text input fields. 我的页面上有一个HTML5画布以及两个文本输入字段。 When the user clicks on the canvas (and only within the canvas), I want to echo the mouse coordinates into the text input boxes on the page. 当用户单击画布(并且仅在画布内)时,我想将鼠标坐标回显到页面上的文本输入框中。 Help?? 救命?? If you need more details, please ask. 如果您需要更多详细信息,请询问。

I found this from a link in the comments below, but can't seem to get it to work?: 我在以下评论中的链接中找到了它,但似乎无法使其正常工作?:

Text inputs: 文字输入:

<input type="number" name="MouseX" id="text_x" min="10" max="600" />

 <input type="number" name="MouseY" id="text_y" min="0" max="480" />

Javascript: 使用Javascript:

<script>
function relMouseCoords(event){
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do{
        totalOffsetX += currentElement.offsetLeft;
        totalOffsetY += currentElement.offsetTop;
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
coords = canvas.relMouseCoords(event);
document.Show.MouseX.value = coords.x;
document.Show.MouseY.value = coords.y;

</script>

UPDATE Here's the code that worked for me: HTML: 更新以下是对我有用的代码:HTML:

<div id="canvasContainer" onclick="point_it(event)">
                          <canvas id="canvas" width="640" height="500">
                            <p>Unfortunately, your browser is currently unsupported by our web 
                              application.  We are sorry for the inconvenience. </p>
                           </canvas>

And JS: 和JS:

<script language="JavaScript">
// Get mouse click coordinates within canvas element
function point_it(event){
    pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("canvasContainer").offsetLeft;
    pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("canvasContainer").offsetTop;
    document.getElementById("canvas").style.left = (pos_x-1) ;
    document.getElementById("canvas").style.top = (pos_y-15) ;
    document.getElementById("canvas").style.visibility = "visible" ;
    document.getElementById("text_x").value = pos_x;
    document.getElementById("text_y").value = pos_y;
}
</script>

You need to add a click event and call your function with the event arguments. 您需要添加一个click事件,并使用事件参数调用函数。

document.getElementById("canvas").onclick = function(event) {
    var coords = canvas.relMouseCoords(event);
    document.getElementById("text_x").value = coords.x;
    document.getElementById("text_y").value = coords.y;
}​​

Live example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM