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

后端 未结 22 2407
忘掉有多难
忘掉有多难 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:53

    According to fresh Quirksmode the clientX and clientY methods are supported in all major browsers. So, here it goes - the good, working code that works in a scrolling div on a page with scrollbars:

    function getCursorPosition(canvas, event) {
    var x, y;
    
    canoffset = $(canvas).offset();
    x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);
    y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;
    
    return [x,y];
    }
    

    This also requires jQuery for $(canvas).offset().

提交回复
热议问题