我的页面上有一个HTML5 Canvas以及两个文本输入字段。当用户单击画布(并且仅在画布内)时,我想将鼠标坐标回显到页面上的文本输入框中。救命??如果您需要更多详细信息,请询问。
我是通过以下评论中的链接找到的,但似乎无法让它发挥作用?:
文字输入:
<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>
答案 0 :(得分:1)
您需要添加一个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;
}