So i just recently got into canvas and decide to play around with it by making a simple game.
However it doesn’t work in chrome but it does work in firefox. The game is supposed to be a very simple RTS. You select a box and when you right click you can move the box from one point to another.
This works in firefox. In chrome however, it draws the boxes but doesn’t register any clicking (can’t select/move boxes). Also in chrome nothing appears in the firebug console. I am running the script off of xampp in case that would be relevant.
EDIT: ha, I’m sorry. I honestly didn’t know where to start looking before so i just posted the whole thing up. I took the above code down and replaced it with a much shorter version below. also edited formatting
EDIT2: narrowed down below code even more
/*Game mouse controls*/
_screen.mousemove(function(e){
var playerUnitHover = _game.onUnit(playerUnits, e),
enemyUnitHover = _game.onUnit(enemyUnits, e);
if(typeof(playerUnitHover)=='number') _screen.css('cursor','pointer');
if(typeof(enemyUnitHover)=='number') _screen.css('cursor','not-allowed');
});
The code above handles the mouse functions. This is where the problems would probably occur. In firebug chrome i can get the variables to show in the console but it fails to register when the cursor is over the box. This is the function below that handles that.
/*If mouse coordinates are ontop of unit, then return index of that unit from supplied array argument*/
this.onUnit = function(array,e){
var numOfUnits = array.length,
mouseOffsetX = e.pageX - offsetX,
mouseOffsetY = e.pageY - offsetY;
for(var i = 0; i < numOfUnits; i++){
var unit = array[i],
xRange = mouseOffsetX > unit.x && (unit.x+unit.width) > mouseOffsetX,
yRange = mouseOffsetY > unit.y && (unit.y+unit.height) > mouseOffsetY;
if (xRange && yRange){
return i;
}
if(!xRange || !yRange) _screen.css('cursor','crosshair');
}
}
The problem is that
is not enough for consistent cross-browser mouse coordinates.
There are probably many valid ways to get mouse coordinates for a canvas. The bullet-proof way that I use might be overcomplicated but it does work in all browsers and is aware of things like CSS borders:
The stylePadding and styleBorder are probably not necessary unless you have padding/border. You can get the canvas’ stylePadding like this: