Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted lines appearing in html5 canvas using tiles

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?

Canvas drawn, but no offset yet. All is fineCanvas drawn w offset, now where did those lines come from?

like image 406
Pedro Avatar asked Mar 30 '12 11:03

Pedro


People also ask

How do you remove lines in canvas?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

What is the tag canvas used for in HTML5?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.

Is canvas introduced in HTML5?

The canvas element was first introduced in HTML5 standard. The drawing is performed in the custom draw() function. It is called when the body of the HTML document is loaded. var canvas = document.


1 Answers

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.

like image 84
AshleysBrain Avatar answered Oct 04 '22 04:10

AshleysBrain