The gap between the figures after scaling

When using scale in HTML5 canvas, I noticed that sometimes there are small gaps between elements. For example:

 context.scale(0.995, 1); context.fillRect(0, 0, 100, 100); context.fillRect(100, 0, 100, 100); 

Without scale, the two rectangles are close to each other, but with a scale between them there is a tiny gap. Is there a way to get rid of it without a rounding factor?

+2
source share
1 answer

As stated in my comment, this is a rendering artifact due to anti-aliasing. As a workaround, you can use the off-screen buffer, which you render without scaling, and then place this image on your original canvas with the correct scaling enabled. If you do, the line should disappear.

The following snippet can give you an idea:

 var buffer = document.createElement('canvas'); buffer.width = 200; buffer.height = 100; var context1 = buffer.getContext('2d'); context1.fillRect(0, 0, 100, 100); context1.fillRect(100, 0, 100, 100); var canvas = document.getElementById('canvasID'); var context = canvas.getContext('2d'); context.scale(0.995, 1); context.drawImage(buffer, 0, 0); context.fillRect(0, 120, 100, 100); context.fillRect(100, 120, 100, 100); 

Compare the top two rectangles in my example (off-screen rendering) with the bottom that were drawn directly on the canvas.

+1
source

All Articles