Obtain co-ordinates of an HTML5 canvas on a page

前端 未结 1 1838
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 22:28

I have a a canvas inside another canvas.

  

its css is something

相关标签:
1条回答
  • 2021-01-28 22:43

    Has your canvas been scrolled?

    If yes, then you also need to account for the distance the canvas has been scrolled in the browser.

    You might check out canvas.getBoundingClientRect() as a way to get the canvas position with the scrolling accounted for:

    function handleMousemove(e){
    
         e.preventDefault();
         e.stopPropagation();
    
         // if the canvas is stationary (not scrolling) then you can do
         // .getBoundingClientRect once at the start of the app
    
         var BB=canvas.getBoundingClientRect();
    
         // calc mouse position based on the bounding box
    
         var mouseX=parseInt(e.clientX-BB.left);
         var mouseY=parseInt(e.clientY-BB.top);
    
         console.log(mouseX+"/"+mouseY);
    
    }
    
    0 讨论(0)
提交回复
热议问题