Michael Lin
Michael Lin

Reputation: 33

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

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 scroll to top of the page. Any ideas?

I used the following code to detecting the clicks/ rollovers -

function defineRollovers() {
    dartsOver = hudCheck(hudLX,dy-(60*units),colHalf,140*units);
    missilesOver = hudCheck(hudLX+colHalf,dy-(60*units),colHalf,140*units);
    explodeOver = hudCheck(dx,dy+(230*units),60*units,50*units);
    dartFireOver = hudCheck(dx+(70*units),dy+(230*units),60*units,50*units);
    missileFireOver = hudCheck(dx+(140*units),dy+(230*units),60*units,50*units);
    rotateYOver = hudCheck(dx-(116*units),fullY-(116*units),108*units,116*units);
    rotateXOver = hudCheck(dx-(224*units),fullY-  (116*units),108*units,116*units);
   }

Upvotes: 0

Views: 244

Answers (1)

markE
markE

Reputation: 105035

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

Upvotes: 2

Related Questions