Multi Layer Canvas HTML5

倖福魔咒の 提交于 2020-01-06 13:55:36

问题


I'm programming a tilebased Game that consists of multiple Layers. However, when i draw the map and try to scale the canvas via CSS, i experience the fact, that the tiles of the upper Layer get a border, which is not intended. the code for drawing the tiles looks like this:

for (var key in Nodes) {
        var currentNode = Nodes[key];
        var tileProb = Math.floor(Math.random() * 10 + 1);

        if (tileProb < 2) {
            currentNode.passable = false;
            canvasLayerZero.drawImage(currentNode.img, 0, 0, tileDim, tileDim, currentNode.x * tileDim, currentNode.y * tileDim, tileDim, tileDim);
        }
        else {
            currentNode.passable = true;
            canvasLayerOne.drawImage(currentNode.img, 20, 0, tileDim, tileDim, currentNode.x * tileDim, currentNode.y * tileDim, tileDim, tileDim);
        };
    };

what the code does is basicly creating a randomized map, consisting of two kinds of tiles: Rock and Grass. The rock-tiles are drawn on the lower canvas and the grass-tiles on the upper one. when the tile-to-be-drawn is a rock it gets its passable propperty set to false. So my problem, as already mentioned, is that when i scale it via css to zoom in, the upper tiles get a border. It does not happen if i draw everything on the same canvas. But i need multiple canvases to be able do "walk" behind walls etc.

Can someone explain me how to get rid of it ?

Thank you in advance!


回答1:


It is due to sub-pixeling.

Default the pixels are drawn at a half pixel offset so when you scale the canvas with CSS (in effect scaling it as an image) this sub-pixeling becomes more visible.

You can try to translate your canvas before drawing the tiles if you need to use CSS:

ctx.translate(-0.5, -0.5);

Generally it's not a good idea to scale a canvas using CSS. Instead see if the context method scale() can help out or resize the tiles before you draw them (cache the new size if speed is essential).



来源:https://stackoverflow.com/questions/19778959/multi-layer-canvas-html5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!