【问题标题】:Insert Mouse Click Coordinates into text input box with Javascript使用Javascript将鼠标点击坐标插入文本输入框
【发布时间】:2012-04-16 06:40:50
【问题描述】:

我的页面上有一个 HTML5 Canvas 以及两个文本输入字段。当用户单击画布(并且仅在画布内)时,我想将鼠标坐标回显到页面上的文本输入框中。帮助??如果您需要更多详细信息,请询问。

我从下面的 cmets 中的链接中找到了这个,但似乎无法让它工作?:

文本输入:

<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:

<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>

更新这是对我有用的代码: 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>

还有 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>

【问题讨论】:

标签: javascript click html5-canvas mouse-coordinates


【解决方案1】:

您需要添加一个点击事件并使用事件参数调用您的函数。

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

【讨论】:

  • 我实际上使用的代码与此稍有不同,但设置类似。我更新了顶部的问题以包含我的最终代码。你能检查它以确保没有任何错误吗?而且,有没有办法只在画布元素中注册一次点击?
  • @adamdehaven 没有错误,但这很容易出错。不要使用你的代码,使用我给你的那个,它会保证你总是得到正确的坐标。我的示例展示了如何仅使用 canvas 元素注册点击。
  • 当我使用您的代码时,它在 jsfiddle 中运行良好,但不会更新我实际站点上的文本输入框...?你能发布我在顶部的完整代码(意思是,使用我的输入名称等)
  • @adamdehaven 我正在使用您的输入名称。唯一的区别是我删除了最大/最小值并将类型更改为“文本”。我已将输入的类型改回“数字”,它仍然有效jsfiddle.net/gAnQq/1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
相关资源
最近更新 更多