Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...