How do I get the coordinates of a mouse click on a canvas element?

后端 未结 22 2372
忘掉有多难
忘掉有多难 2020-11-21 23:56

What\'s the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No

相关标签:
22条回答
  • 2020-11-22 00:33

    I recommend this link- http://miloq.blogspot.in/2011/05/coordinates-mouse-click-canvas.html

    <style type="text/css">
    
      #canvas{background-color: #000;}
    
    </style>
    
    <script type="text/javascript">
    
      document.addEventListener("DOMContentLoaded", init, false);
    
      function init()
      {
        var canvas = document.getElementById("canvas");
        canvas.addEventListener("mousedown", getPosition, false);
      }
    
      function getPosition(event)
      {
        var x = new Number();
        var y = new Number();
        var canvas = document.getElementById("canvas");
    
        if (event.x != undefined && event.y != undefined)
        {
          x = event.x;
          y = event.y;
        }
        else // Firefox method to get the position
        {
          x = event.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = event.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }
    
        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;
    
        alert("x: " + x + "  y: " + y);
      }
    
    </script>
    
    0 讨论(0)
  • 2020-11-22 00:33

    In Prototype, use cumulativeOffset() to do the recursive summation as mentioned by Ryan Artecona above.

    http://www.prototypejs.org/api/element/cumulativeoffset

    0 讨论(0)
  • 2020-11-22 00:34

    Edit 2018: This answer is pretty old and it uses checks for old browsers that are not necessary anymore, as the clientX and clientY properties work in all current browsers. You might want to check out Patriques Answer for a simpler, more recent solution.

    Original Answer:
    As described in an article i found back then but exists no longer:

    var x;
    var y;
    if (e.pageX || e.pageY) { 
      x = e.pageX;
      y = e.pageY;
    }
    else { 
      x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
      y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    } 
    x -= gCanvasElement.offsetLeft;
    y -= gCanvasElement.offsetTop;
    

    Worked perfectly fine for me.

    0 讨论(0)
  • 2020-11-22 00:34

    Update (5/5/16): patriques' answer should be used instead, as it's both simpler and more reliable.


    Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div element containing the canvas with a position: relative style applied. To account for this you need to loop through the chain of offsetParents, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.

    function relMouseCoords(event){
        var totalOffsetX = 0;
        var totalOffsetY = 0;
        var canvasX = 0;
        var canvasY = 0;
        var currentElement = this;
    
        do{
            totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
            totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
        }
        while(currentElement = currentElement.offsetParent)
    
        canvasX = event.pageX - totalOffsetX;
        canvasY = event.pageY - totalOffsetY;
    
        return {x:canvasX, y:canvasY}
    }
    HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
    

    The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is

    coords = canvas.relMouseCoords(event);
    canvasX = coords.x;
    canvasY = coords.y;
    
    0 讨论(0)
  • 2020-11-22 00:36

    If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.

    function getCursorPosition(canvas, event) {
        const rect = canvas.getBoundingClientRect()
        const x = event.clientX - rect.left
        const y = event.clientY - rect.top
        console.log("x: " + x + " y: " + y)
    }
    
    const canvas = document.querySelector('canvas')
    canvas.addEventListener('mousedown', function(e) {
        getCursorPosition(canvas, e)
    })
    
    0 讨论(0)
  • 2020-11-22 00:36

    ThreeJS r77

    var x = event.offsetX == undefined ? event.layerX : event.offsetX;
    var y = event.offsetY == undefined ? event.layerY : event.offsetY;
    
    mouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;
    mouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;
    

    After trying many solutions. This worked for me. Might help someone else hence posting. Got it from here

    0 讨论(0)
提交回复
热议问题