Unwanted lines appearing in html5 canvas using tiles

回眸只為那壹抹淺笑 提交于 2020-01-02 01:30:13

问题


I'm drawing a map on a canvas using squares 40px * 40px. All is well until I, by offsetting the canvas (using transform), scroll the map. Then, out of nowhere, lines apear between the tiles. See images below.

Why?


回答1:


This looks like floating-point positioning (e.g. you've scrolled to 100.5, 100.5) combined with bilinear filtering most browsers use to display images on the 2D canvas.

Basically, if you drawImage() an image between pixels, every pixel is smoothed over two pixels, which means the edges draw at 50% alpha over the background. This breaks tiling, because the next tile's edge is the same, and draws at 50% alpha over the other tile's 50% alpha, which adds up to 75% alpha. This will appear lighter or darker (depending on the background color) than the rest of the tile. So you get "seams" along the edges of the tiles.

To fix: Math.round() your image co-ordinates, as well as any calls to translate() (since translating by half a pixel has the same effect). This guarantees everything is drawn to a pixel-aligned grid and never seams.



来源:https://stackoverflow.com/questions/9942209/unwanted-lines-appearing-in-html5-canvas-using-tiles

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