我的頁面上有一個HTML5 Canvas以及兩個文本輸入字段。當用戶點擊畫布(並且只在畫布內)時,我想將鼠標座標回顯到頁面上的文本輸入框中。幫幫我??如果你需要更多的細節,請詢問。將鼠標點擊座標到Javascript的文本輸入框中
我發現這個在下面的評論的鏈接,但似乎無法得到它的工作?:
文本輸入:
<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>
UPDATE以下是我工作的代碼: 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>
你想要的鼠標到畫布或文檔座標關係嗎? – j08691 2012-04-02 15:34:39
您可以在http://www.javascriptsource.com/page-details/mouse-coordinates.html找到與您想要的內容非常相似的內容 - 但不使用HTML5 Canvas。 – 2012-04-02 15:38:05
@JoshLee我發現這個http://www.w3schools.com/html5/html5_canvas.asp如果你滾動到畫布的例子,他們顯示的座標。我沒有真正嘗試過任何東西,因爲我不知道從哪裏開始 – adamdehaven 2012-04-02 15:39:09