0

I have seen a few related posts on here but, from what I can understand, non that really fit my use case.

I have been reading this post on how to make a responsive canvas game and have followed the logic in step 1 and 2 and have positioned my canvas in the centre of the screen using the following:

<div id='game-screen'></div>

#game-screen {
    position: absolute;
    top: 50%;
    left: 50%;
    translate: transform(-50%, -50%);
}

The div is what contains the canvas created in my Javascript.

I have my canvas width and height different to the "styled" width and height as per this tutorial. My canvas width and height is 1280 x 1024 pixels.

Now the problem I am having is that when binding my mouse move event to the canvas, the event.pageX and event.pageY variables are not proportionate to the scaled canvas. I have taken into consideration the offset left and top but I am unsure as to how I could "scale" the mouse x and y to relate to the canvas aspect ratio?

There seems to be around a 5-20px difference based on the stretched canvas size.

Thank you in advance, I hope this makes sense.

1 Answers1

0

You can use getBoundingClientRect() to get the game screen position into the document. So with a substraction, you can get the relative mouse position.

var gameScreen = document.getElementById('game-screen');
gameScreen.addEventListener('click', function(event) {
  var gameScreenPosition = gameScreen.getBoundingClientRect();
  var x = event.clientX - gameScreenPosition.left;
  var y = event.clientY - gameScreenPosition.top;
  alert(x + ' ' + y);
})

Example : https://jsfiddle.net/tzi/2cj8n8xt/

tzi
  • 8,719
  • 2
  • 25
  • 45