Canvas drawImage - firefox/opera/ie(不是chrome)中瓷砖的可见边缘 [英] Canvas drawImage - visible edges of tiles in firefox/opera/ie (not chrome)

查看:17
本文介绍了Canvas drawImage - firefox/opera/ie(不是chrome)中瓷砖的可见边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在画布上绘制游戏地图.地面由瓷砖组成 - 简单的 64x64 png 图像.

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

当我在 Chrome 中绘制它时,它看起来没问题(左),但是当我在 Firefox/Opera/IE 中绘制它(右)时,我得到了可见的边缘:

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

当我使用四舍五入的数字时问题就消失了:

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);//所以不是夹紧问题
  2. ctx.imageSmoothingEnabled = false;
  3. 图像渲染:-moz-crisp-edges;(css)

有没有办法让它在 ff/op/ie 中工作?

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

向宽度/高度添加 1 个像素并按比例补偿它(宽度+1/比例)似乎有所帮助:

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:

推荐答案

最简单的解决方案(我认为最有效)是在绘制游戏的背景图块.

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.

例如:

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";

之前:http://jsfiddle.net/d9MSV

之后:http://jsfiddle.net/d9MSV/1/

注意正如提问者指出的那样,额外的像素需要考虑缩放,因此更正确的解决方案是他的修改:http://jsfiddle.net/d9MSV/3/

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/

这篇关于Canvas drawImage - firefox/opera/ie(不是chrome)中瓷砖的可见边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆