I'm relatively new to JavaScript and to get a grip on it I've been working on a 3D engine and I stumbled on something odd. When I render a filled mesh with wire-frame disabled, a gap shows up between my triangles.
Here's an example:
// vertices
var v1 = [40,20];
var v2 = [125,35];
var v3 = [165,105];
var v4 = [35,95];
// draw on screen 1
var canvas = document.getElementById("screen");
var context = canvas.getContext("2d");
triangle(v1,v2,v3,context,true);
triangle(v3,v4,v1,context,true);
// draw on screen 2
var canvas = document.getElementById("screen2");
var context = canvas.getContext("2d");
triangle(v1,v2,v3,context,false);
triangle(v3,v4,v1,context,false);
// draw triangle method
function triangle(v1,v2,v3, context,wireframe)
{
context.beginPath();
context.moveTo(v1[0],v1[1]);
context.lineTo(v2[0],v2[1]);
context.lineTo(v3[0],v3[1]);
context.lineTo(v1[0],v1[1]);
context.closePath();
context.fillStyle = "#333";
context.fill();
if (wireframe)
{
context.strokeStyle = "#0f3";
context.stroke();
}
}
body
{
background-color: #ddd;
}
canvas
{
border:2px solid #000;
}
<canvas id="screen" width="200" height="150" ></canvas>
<canvas id="screen2" width="200" height="150"></canvas>
In essence, the two polygons don't seem to connect properly.
- Making the wire-frame the same colour as triangle is not a solution. I want to apply a texture without seeing the edge.
- Drawing connected polygons isn't a solution, each triangle may have its own texture transformation.
- Should I overdraw triangles to close the gaps?
- Is this an Anti-Aliasing issue?
Thanks in advance.
Above: Shows gap between triangles when the wire-frame has been disabled
UPDATE 9-apr-2017
I've considered various options to solve my issue, including writing a triangle routine. Picture down below. However, drawing two triangles tanks my FPS quite a lot. I need a faster way to put pixels on the canvas, but that's for another post since it's off topic.
However, I think that expanding the triangle half a pixel is a better/faster solution since the fill() method is executed by the browser internally instead of JavaScript.