Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas drawImage - visible edges of tiles in firefox/opera/ie (not chrome)

I'm drawing a game map into canvas. The ground is made of tiles - simple 64x64 png images.

When I draw it in Chrome, it looks ok (left), but when I draw it in Firefox/Opera/IE (right), I get visible edges: enter image description here

The problem disappears when I use rounded numbers:

ctx.drawImage(img, parseInt(x), parseInt(y), w, h);

But that doesn't help when I use scaling:

ctx.scale(scale); // anything from 0.1 to 2.0

I also tried these, but no change:

  1. ctx.drawImage(img, 5, 5, 50, 50, x, y, w, h); // so not an issue of clamping
  2. ctx.imageSmoothingEnabled = false;
  3. image-rendering: -moz-crisp-edges; (css)

Is there any way to make it work in ff/op/ie?


Edit: Partial solution found

Adding 1 pixel to width/height and compensating it by scale (width+1/scale) seems to help:

ctx.drawImage(props.img, 0, 0, width + 1/scale, height + 1/scale);

It makes some artifacts, but I think it's acceptable. On this image, you can see green tiles without edges, and blue windows, which are not compensated, still with visible edges:

fixed

like image 824
psycho brm Avatar asked Oct 03 '22 12:10

psycho brm


1 Answers

The simplest solution (and I'd argue most effective) is to use tiles that have a 1 pixel overlap (are either 1x1 or 2x2 larger) when drawing the background tiles of your game.

Nothing fancy, just draw slightly more than you would normally. This avoids complications and performance considerations of bringing extra transformations into the mix.

For example:

var img = new Image();
img.onload = function () {
    for (var x = 0.3; x < 200; x += 15) {
        for (var y = 0.3; y < 200; y += 15) {
            ctx.drawImage(img, 0, 0, 15, 15, x, y, 15, 15);
            // If we merely use 16x16 tiles instead,
            // this will never happen:
            //ctx.drawImage(img, 0, 0, 16, 16, x, y, 16, 16);
        }
    }
}
img.src = "http://upload.wikimedia.org/wikipedia/en/thumb/0/06/Neptune.jpg/100px-Neptune.jpg";

Before: http://jsfiddle.net/d9MSV

And after: http://jsfiddle.net/d9MSV/1/


Note as the asker pointed out, the extra pixel needs to account for scaling, so a more correct solution is his modification: http://jsfiddle.net/d9MSV/3/

like image 82
Simon Sarris Avatar answered Oct 07 '22 18:10

Simon Sarris