Pregunta

I have an HTML5 Canvas on my page along with two text input fields. 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:

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

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

<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>
¿Fue útil?

Solución

You need to add a click event and call your function with the event arguments.

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top