Javascript Canvas Cordova - 等距瓷砖留下线条

时间:2016-07-04 09:05:10

标签: javascript cordova canvas tiles isometric

我正在尝试制作游戏等距风格,但是当我绘制瓷砖时,它们会在

之间留下线条

我的设备的画布参数是2560w 1440h。我做了数学,没有看到任何浮点数,没有分数。我仍然尝试在坐标上使用Math.round,但没有区别

我尝试过增加原始图块图像尺寸的大小:64x40,128x80 256x160& 512x320。线条似乎变得越来越好,但我能在多大程度上制作我的瓷砖?

我已经检查了这篇文章,但我认为同样的逻辑并不适用于等距:

链接:Unwanted lines apearing in html5 canvas using tiles

我不知道如何解决这个问题

更新

如果我在瓷砖上取下侧面,只留下顶部,我会得到白线(来自白色背景)

如果我用纯红色填充整个瓷砖和侧面,则没有更多的线

瓷砖

enter image description here

预览

Preview

for(var i = 0; i < 50; i++){
    for(var j = 0; j < 50; j++){
        ctx.drawImage(isometricTile,
                      (c.width/2 - c.width/20) + (c.width/20 * i) + (-c.width/20 * j),
                      (c.width/40 * i) + (c.width/40 * j),
                       c.width/10,
                       c.width/10 * 0.625);
}

1 个答案:

答案 0 :(得分:0)

抗锯齿问题

线条是由于您正在绘制的形状边缘的抗锯齿造成的。

平铺预渲染修复。

对于基于图块的游戏,您应该尽可能多地渲染到屏幕外的画布,并使用这些图像渲染到显示器。执行此操作将允许您扫描图像并增加或减少alpha,以便边缘不再消除锯齿。只有瓷砖底部(z深度)4边的边缘需要固定。

Aliased edges

图像显示需要修复的像素。您必须检查像素是在标题等距区域内部还是外部。需要完全移除外部的像素,其内部的像素具有α<1。 255需要将alpha设置为255。

此修复只需要发生一次。如果标题没有动画并且不在客户端之间更改,则可以在制作期间完成此操作,并将图块集作为图像传送。

创建屏幕外画布

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&lt; 255将替换现有的像素,而不是让它们显示出来。

将图块画布渲染到显示

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
)

通过渲染cludge修复。

如果需要实时渲染切片,则修复方法是添加与填充相同颜色的小轮廓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代码段显示了解决问题的各种方法的结果。