开发者

Drawing Images on Html5 Canvas at floating point coordinates

开发者 https://www.devze.com 2023-03-29 07:07 出处:网络
As you know using rounded coordinates while drawing on canvas is faster. Also floating coordinates may cause unintended gaps on canvas. For example, you are drawing google map tiles to canvas, 256x256

As you know using rounded coordinates while drawing on canvas is faster. Also floating coordinates may cause unintended gaps on canvas. For example, you are drawing google map tiles to canvas, 256x256 tiles work well, if the starting coordinates are integer. If not, to avoid one pixel unpainted lines, you should round the coordinates.

Here, that's Ok.

But, what if you should use scaling, transformation over canvas, how can you round the coordinates?

e.g.

 ctx.drawImage(image, round(x), round(y), 256, 256开发者_C百科); 

is OK.

But what if

  ctx.scale(1.0/65536);
  ctx.translate(118079.4);
  ctx.drawImage(image, x, y, 256, 256); // where x and y are integers like 118413

The image will be drawn into floating coordinates. How can I round that coordinates?


The reason that drawing images with floating point coordinates is slow is not because using integers for the coordinates and transformations is faster, but that because of the fraction component of the coordinate the images will be resampled to different pixel positions.

This resampling does not need to happen for images drawn at integer coordinates (with 100% scaling) and is likely a fast path for the image drawing code. If you are doing any scaling, rotation or non-integer translation, the slower image resampling routine may be used.

One way of dealing with gaps between images with floating point coordinates is to make the images slightly larger to cover the gaps, or, render all the visible tiles with rounded coordinates into an hidden un-rotated canvas and then draw that, rotated and scaled, into the visible one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号