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

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

    Here is some modifications of the above Ryan Artecona's solution.

    function myGetPxStyle(e,p)
    {
        var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:"";
        return parseFloat(r);
    }
    
    function myGetClick=function(ev)
    {
        // {x:ev.layerX,y:ev.layerY} doesn't work when zooming with mac chrome 27
        // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21
        // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad
        // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)
        // html.offsetX and html.offsetY don't work with mac firefox 21
    
        var offsetX=0,offsetY=0,e=this,x,y;
        var htmls=document.getElementsByTagName("html"),html=(htmls?htmls[0]:0);
    
        do
        {
            offsetX+=e.offsetLeft-e.scrollLeft;
            offsetY+=e.offsetTop-e.scrollTop;
        } while (e=e.offsetParent);
    
        if (html)
        {
            offsetX+=myGetPxStyle(html,"marginLeft");
            offsetY+=myGetPxStyle(html,"marginTop");
        }
    
        x=ev.pageX-offsetX-document.body.scrollLeft;
        y=ev.pageY-offsetY-document.body.scrollTop;
        return {x:x,y:y};
    }
    

提交回复
热议问题