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

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

    Here is a simplified solution (this doesn't work with borders/scrolling):

    function click(event) {
        const bound = event.target.getBoundingClientRect();
    
        const xMult = bound.width / can.width;
        const yMult = bound.height / can.height;
    
        return {
            x: Math.floor(event.offsetX / xMult),
            y: Math.floor(event.offsetY / yMult),
        };
    }
    

提交回复
热议问题