抗锯齿问题
线条是由于您正在绘制的形状边缘的抗锯齿。
平铺预渲染修复。
对于基于图块的游戏,您应该尽可能多地渲染到离屏画布上,并使用这些图像渲染到显示器上。这样做将允许您扫描图像并增加或减少 alpha,从而使边缘不再抗锯齿。只有瓷砖底部(z 深度)4 侧的边缘需要修复。
图像显示需要修复的像素。您必须检查像素是在标题等距区域之内还是之外。外部的像素需要完全移除,内部的 alpha
此修复只需要发生一次。如果标题没有动画并且在客户端之间没有变化,那么这可以在制作过程中完成,并且瓷砖集作为图像交付。
创建一个离屏画布
var tiles = document.createElement(canvas);
var tiles.width = tiles.height = 256;
var tiles.ctx = tiles.getContext("2d");
然后使用上下文创建瓦片,然后就可以得到像素数据了
var imgData = tiles.ctx.getImageData(0,0,256,256);
数组 imgData.data 为每个像素保存 4 个字节,红色、绿色、蓝色和 alpha 各有一个,范围为 0 - 256。
将像素地址转换为数组索引
var pixelIndex = Math.floor(x) * 4 + Math.floor(y) * imgData.width;
获取像素数据
var r,g,b,a;
r = imgData.data[pixelIndex];
g = imgData.data[pixelIndex + 1];
b = imgData.data[pixelIndex + 2];
a = imgData.data[pixelIndex + 3];
设置一个像素
imgData.data[pixelIndex] = r;
imgData.data[pixelIndex + 1] = g;
imgData.data[pixelIndex + 2] = b;
imgData.data[pixelIndex + 3] = a;
数组类型的数组是一个固定的 8 位无符号值。这意味着值会自动向下舍入,如果小于或大于 0 - 255,它们将分别钳制为 0、255。
将像素放回图像中
tiles.ctx.putImageData(pixelData,0,0);
与绘制命令不同,所有像素都会被替换,因此 alpha
将磁贴画布渲染到显示器
var tilePos = { // where on the tiles image the tile is
x : 64,
y : 64,
w : 128,
h : 64,
}
var screenPos = { // where on the screen to draw the tile
x : 100,
y : 100,
}
ctx.drawImage( // render function
tiles, // source image
tilePos.x, // source rect to get pixels to render
tilePos.y,
tilePos.w,
tilePos.h,
screenPos.x, // destination location
screenPos.y,
tilePos.w,
tilePos.h
)
通过渲染结块修复。
如果需要实时渲染图块,则解决方法是添加与填充颜色相同的小轮廓ctx.lineWidth = 0.5,然后仅从像素中心绘制。 ctx.lineTo(Math.floor(x) + 0.5, Math.floor(y) + 0.5) 这将完全删除显示的背景。
更详细的看这个问题How to draw on Canvas more precisely to avoid background leaking from underneeth代码sn-p显示了解决问题的各种方法的结果。