Skip to content Skip to sidebar Skip to footer

Why Are The 'pixels' On My Scaled HTML5 Canvas Strangely Aligned?

I'm currently writing a little HTML5 canvas/JS based snake clone similar to the classic Nokia Snake. (This is my first HTML5 canvas/JS game as well as my first game, I'm still a no

Solution 1:

The problem comes from anti-aliasing / sub-pixeling.

Your cherry is placed in the board at a random value. The problem with the random value is that it's a float value so the cherry will be placed offset with some decimals and therefor sub-pixeled by the browser.

When using scale the result of this sub-pixeling is also scaled (which is more clear when you change its color to for example white) and the result is that it doesn't match the grid.

To solve this simply force the x and y position of the cherry to integer, for example like this:

var cherry = {
  color: "#B1001D",
  x: Math.random()*65|0,
  y: Math.random()*65|0
}

Fiddle here

| is the bitwise OR operator which forces the number first to an integer in order to be able to use bitwise OR. Since we OR with 0, the output is the same (beyond cutting the float decimal).


Post a Comment for "Why Are The 'pixels' On My Scaled HTML5 Canvas Strangely Aligned?"