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

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

    Here is a small modification to Ryan Artecona's answer for canvases with a variable (%) width:

     HTMLCanvasElement.prototype.relMouseCoords = function (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;
    
        // Fix for variable canvas width
        canvasX = Math.round( canvasX * (this.width / this.offsetWidth) );
        canvasY = Math.round( canvasY * (this.height / this.offsetHeight) );
    
        return {x:canvasX, y:canvasY}
    }
    

提交回复
热议问题