• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

HTML5 HTML5 mouse coordinates are offset when browser is scrolled.

orbian

Member
Hi,

I am having issues with an HTML5 game. The game is 800x600 and is centered in the browser window. Even though the canvas is completely within the visible region of the browser page the browser still adds scrollbars. If these move at all then the mouse coordinates in the canvas will be offset by that amount. This means the mouse press events won't trigger at the right location (You now have to click to the side of an object to get it to trigger).

I've added a couple of images to show the offset. When the scrollbars are at zero then clicking the lower right of the canvas should show something close to 800,600. When the scrollbar is moved then clicking the bottom right of the canvas shows a value that is offset by the amount the scrollbar moved.

In the past, when hand coding HTML5 JavaScript I would offset the mouse coordinates using the canvas bounding rect:
Code:
function getMousePos(canvas, evt) {
   var rect = canvas.getBoundingClientRect();
   return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
   };
}

canvas.addEventListener('click', function (evt) {
   var mousePos = getMousePos(canvas, evt);
   gameTapped(mousePos);
}, false);
In Gamemaker I am relying on the mouse events to interact with objects so I am not able to readjust the coordinates. Basically, the wrong things get clicked on when the scrollbars get moved.

Thanks,
Bob
 

Attachments

orbian

Member
Hi,

I am using GSM 2. I've noticed that is happens on Microsoft Edge because it puts up scrollbars easily. Chrome and Firefox don't seem to put up scrollbars because the canvas doesn't go to the edges (I make it 90%). But mobile devices like iOS can cause issues. Especially in landscape mode.

using JavaScript with an extension calling canvas.getBoundingClientRect() and window.innerWidth I can pretty much figure out what the offset is but it doesn't help with the mousing events since they will never fire because the user is essentially clicking in the wrong place.

Thanks
 
Top