Drawing Images on Html5 Canvas at floating point coordinates

喜夏-厌秋 提交于 2019-12-21 20:47:43

问题


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); 

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?


回答1:


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.



来源:https://stackoverflow.com/questions/7114205/drawing-images-on-html5-canvas-at-floating-point-coordinates

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