I recognize that Canvas drawImage is inexplicably offset by 1 Pixel is a very similar issue, but I was already applying the advice given in that question's answer before I even came across this problem.
I'm implementing a sprite sheet system for an HTML5-based game. Individual frames are defined simply:
frame = new AnimationFrame(img, x, y, w, h);
Inside the AnimationFrame constructor, all of the numeric parameters are truncated to integers.
Then when I go to draw it on the canvas, I use what should also be simple code:
context.drawImage(frame.img,
frame.x,
frame.y,
frame.w,
frame.h,
this.position.x | 0,
this.position.y | 0,
frame.w,
frame.h,
);
Unfortunately, I get different results in different browsers.
In Chrome on Mac and Firefox on Mac, slicing the sprite sheet this way causes the individual frames to be offset by half a pixel, causing the top edge of the character's head to be drawn too thin and the top of the next sprite down to peek into the bottom of this one.
I can accommodate this problem with frame.x - 0.5
and frame.y - 0.5
but if I do that then I get the opposite problem in Safari on Mac and iOS and in Firefox on Windows.
I don't particularly WANT to do a browser detect to decide how to nudge the coordinate system, so I'm looking for suggestions for a way to either (1) force the various browsers to behave the same way, or (2) detect the issue at page load time with a test so I can just store the pixel grid offset in a variable.
NB: I'm going for a chunky pixel aesthetic, so my canvas is scaled by a factor of 2. This works fine without blurring, but it makes the half-pixel issue more clearly visible. Without scaling, the edges of the sprite still get distorted, so that's not the problem.