11

I'm drawing a map on a canvas using squares 40px * 40px. All is well until I, by offsetting the canvas (using transform), scroll the map. Then, out of nowhere, lines apear between the tiles. See images below.

Why?

Canvas drawn, but no offset yet. All is fine Canvas drawn w offset, now where did those lines come from?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pedro
  • 474
  • 1
  • 3
  • 11

1 Answers1

19

This looks like floating-point positioning (e.g. you've scrolled to 100.5, 100.5) combined with bilinear filtering most browsers use to display images on the 2D canvas.

Basically, if you drawImage() an image between pixels, every pixel is smoothed over two pixels, which means the edges draw at 50% alpha over the background. This breaks tiling, because the next tile's edge is the same, and draws at 50% alpha over the other tile's 50% alpha, which adds up to 75% alpha. This will appear lighter or darker (depending on the background color) than the rest of the tile. So you get "seams" along the edges of the tiles.

To fix: Math.round() your image co-ordinates, as well as any calls to translate() (since translating by half a pixel has the same effect). This guarantees everything is drawn to a pixel-aligned grid and never seams.

AshleysBrain
  • 22,335
  • 15
  • 88
  • 124
  • 1
    Yes, I found this one out myself actually - and your answer is spot on. Turns out if you use anything else than an integer to offset the canvas, these lines apear. So I simply used a Math.floor(offsetX) and solved the issue. – Pedro Mar 30 '12 at 12:25