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

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

    Using jQuery in 2016, to get click coordinates relative to the canvas, I do:

    $(canvas).click(function(jqEvent) {
        var coords = {
            x: jqEvent.pageX - $(canvas).offset().left,
            y: jqEvent.pageY - $(canvas).offset().top
        };
    });
    

    This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.

    Note that if your canvas is scaled then these coordinates are not the same as canvas logical coordinates. To get those, you would also do:

    var logicalCoords = {
        x: coords.x * (canvas.width / $(canvas).width()),
        y: coords.y * (canvas.height / $(canvas).height())
    }
    

提交回复
热议问题