0

I was exploring some drawing on the HTML canvas, and quickly landed at dissecting my shapes into triangles, as that seem to be the most common and sure way to ensure that one is handling only simple polygons and not self-intersection ones (which get drawn in a somewhat uncontrollable fashion to me).

But when I wanted to draw a simple rectangle as to triangles, I got the following result: enter image description here

The approach I am taken is the following:

const rect = [{
  x: 200,
  y: 225
}, {
  x: 490,
  y: 225
}, {
  x: 490,
  y: 375
}, {
  x: 200,
  y: 375
}];

const triangle1 = [rect[0], rect[1], rect[2]];
const triangle2 = [rect[0], rect[2], rect[3]];

fillPolygon(ctx, triangle1, 'blue');
fillPolygon(ctx, triangle2, 'blue');

See the full example here: https://jsfiddle.net/JLVva/85/

Since triangles seem to be the basis of graphics drawing, I think I am missing a common workaround applied in these scenarios. How is this normally handled?

Timm
  • 2,652
  • 2
  • 25
  • 34

1 Answers1

0

If you also add a stroke to the shape as well as a fill it removes that gap. I assume the stroke defaults to transparent or something.

Add this to the end of your fillPolygon function.

ctx.strokeStyle = color;
ctx.stroke();
Razzildinho
  • 2,564
  • 1
  • 19
  • 32
  • Since I never stroke, I don't think anything white/transparent gets drawn. – Timm Apr 20 '17 at 09:42
  • But I think your idea might solve the problem, because it makes the triangles just a tiny bit bigger (assuming a stroke width of 1). I have found others suggesting just increasing the size of the shape "a little" so that they overlap, but I don't feel like that can be the final solution as it's very imprecise and might lead to inconsistent results (imagine every triangle having a different color. If you were to count all the pixel by color, you should get the same amount, not a few more of the last one drawn). – Timm Apr 20 '17 at 09:43
  • I'm not sure but I would say there is either a stroke applied automatically or a gap left for the stroke and that's why you get that hairline. – Razzildinho Apr 20 '17 at 09:45