多层帆布HTML5 [英] Multi Layer Canvas HTML5
问题描述
我正在编写一个由多个图层组成的基于图块的游戏。
但是,当我绘制地图并尝试通过CSS缩放画布时,我体验到了这一事实,即上层的图块会获得一个边框,而这并非意图。
绘制图块的代码如下所示:
for(var key in Nodes){
var currentNode =节点[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);
};
};
代码的作用是基本创建一个随机地图,由两种拼贴组成:Rock and Grass 。岩石砖被绘制在较低的画布上,而上部的草地砖被绘制。
当要绘制的图块是一块岩石时,它的可传递属性设置为false。
所以我的问题,正如已经提到的那样,当我通过css进行缩放以放大时,上方的图块会显示边框。如果我在同一个画布上绘制所有内容,它不会发生。但我需要多个画布才能在墙壁等后面走路。
有人可以解释我如何摆脱它吗?
预先感谢您!
这是由于子像素化。
默认情况下,像素以半像素偏移绘制,所以当您使用CSS缩放画布时(实际上将其缩放为图像),此子像素变得更加明显。 b
$ b
如果您需要使用CSS,您可以在绘制图块之前尝试翻译您的画布:
ctx.translate(-0.5,-0.5);
通常,使用CSS缩放画布并不是一个好主意。相反,看看上下文方法 scale()
是否可以在绘制之前帮助或调整大小(如果速度很重要,请缓存新大小)。
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!
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).
这篇关于多层帆布HTML5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!