HTML5 Canvas - Buttons doesn't work once scroll down the page

后端 未结 1 1461
栀梦
栀梦 2021-01-28 05:41

I used HTML canvas to create a gun model as well as the control buttons (e.g. fire buttons), but the buttons doesn\'t work once scrolls the page down, the buttons only work when

相关标签:
1条回答
  • 2021-01-28 06:41

    You must account for the distance that your canvas element has scrolled when calculating the mouse position.

    You can use getBoundingClientRect to get the top position of your canvas after accounting for scrolling.

    BB=canvas.getBoundingClientRect();
    var offsetY = BB.top;
    

    Then you can accurately calculate the mouse position within your canvas like this:

    function handleMouseMove(e){
    
        // get the bounding box of the canvas
        // relative to the scrolled window
        BB=canvas.getBoundingClientRect();
        var offsetX=BB.left;
        var offsetY=BB.top;
    
        // get the mouse position relative to the canvas
        mouseX=parseInt(e.clientX-offsetX);
        mouseY=parseInt(e.clientY-offsetY);
    }
    

    You can get better performance if you calculate offsetX & offsetY only in response to the window's scroll event. That way you don't have to do getBoundingClientRect with every mouse event.

    window.onscroll=function(e){
        var BB=canvas.getBoundingClientRect();
        offsetX=BB.left;
        offsetY=BB.top;
    }
    
    0 讨论(0)
提交回复
热议问题