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
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;
}