bo_knows
bo_knows

Reputation: 866

Canvas click events screwed up when browser window shrinks/moves

I've been playing around with creating a hexagonal grid in HTML5 Canvas. I have a basic grid, where if you click a hex it will highlight the hex (demo here: http://cfiresim.com/hex-map-game-reboot/test.html)

In javascript, I am defining the canvas as such (some parts omitted for brevity):

 var hex = {};
 hex.canvas = document.getElementById("HexCanvas");
 hex.ctx = null;
 console.log("Initializing new game...");
 this.radius = 20;
 this.side = Math.round((3 / 2) * this.radius);
 this.height = Math.round(Math.sqrt(3) * this.radius);
 this.width = Math.round(2 * this.radius);

 //Set Size of main div to size of canvas
 $('#primary-panel').css('height', (hex.height * hex.rows)+hex.height*2);
 hex.canvas.style.width='100%';
 hex.canvas.style.height='100%';
 hex.canvas.width  = hex.canvas.offsetWidth;
 hex.canvas.height = hex.canvas.offsetHeight;

 //Set click eventlistener for canvas
 this.canvas.addEventListener("mousedown", this.clickEvent.bind(this), false);

 this.ctx = this.canvas.getContext('2d');

All of the code can be found here: https://github.com/boknows/hex-map-game-reboot

My primary question is: Is there a specific way to prevent the click events from getting all screwy when the canvas is resized via the browser? For example, if you shrink the browser to be just bigger than the grid, clicks dont register in the right place. Am I missing some feature of canvas? Maybe getSelectedTile() is not being defined correctly?

Edit: It seems like this primarily happens when the browser scrolls a little, and thus moves the grid off screen. The clicks then register with a weird offset, which I'm guessing is equal to the distance the screen scrolled. Advice?

Upvotes: 3

Views: 183

Answers (1)

Qbic
Qbic

Reputation: 298

You must take into a position of a page scroll.

In HexagonGrid.js, instead of this:

hex.clickEvent = function(e) {
        var mouseX = e.pageX;
        var mouseY = e.pageY;

Do this:

hex.clickEvent = function(e) {
        var mouseX = e.pageX - window.pageXOffset;
        var mouseY = e.pageY - window.pageYOffset;

Upvotes: 4

Related Questions