javascript - Canvas click events screwed up when browser window shrinks/moves -
i've been playing around creating hexagonal grid in html5 canvas. have basic grid, if click hex highlight hex (demo here: http://cfiresim.com/hex-map-game-reboot/test.html)
in javascript, defining canvas such (some parts omitted 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 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 canvas this.canvas.addeventlistener("mousedown", this.clickevent.bind(this), false); this.ctx = this.canvas.getcontext('2d'); all of code can found here: https://github.com/boknows/hex-map-game-reboot
my primary question is: there specific way prevent click events getting screwy when canvas resized via browser? example, if shrink browser bigger grid, clicks dont register in right place. missing feature of canvas? maybe getselectedtile() not being defined correctly?
edit: seems happens when browser scrolls little, , moves grid off screen. clicks register weird offset, i'm guessing equal distance screen scrolled. advice?
you must take position of 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;
Comments
Post a Comment