There are two kind of paths in canvas, the main path and then sub-paths.
For a close to work you need to only have max one sub-path. Every time moveTo() is used a new sub-path will be created so when a line is made like this:
moveTo(x1, y1);
lineTo(x2, y2);
moveTo(x2, y2);
lineTo(x3, y3);
You have two sub-paths that are not connected. What you want is to continue adding lines to the existing sub-paths like this:
moveTo(x1, y1);
lineTo(x2, y2);
lineTo(x3, y3);
Now it is possible to close the shape connecting x3->x1 and y3->y1.
Using ctx.beginPath() in this case makes it worst. It will clear all sub-paths added to the main path.
What you need to do is to globally (or at some higher level) create a new path using beginPath() (every time you need to redraw the content for example).
Then the first line needs to be set using moveTo(). Then every other lines using lineTo().
Finally you can use closePath() and render it using stroke() or fill() (closePath() is not needed with fill, with stroke it must be called before stroke).
For example (untested, adopt as needed):
function draw() { //this function draw the lines
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x,y;
canvas.width = table.offsetWidth;
canvas.height = table.offsetHeight;
function connect(image, index) { //this function link the images
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;
index === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
// new path here
ctx.beginPath();
for(var i=0; i
connect( images[i], i); // provide index so we can sep. move/line
}
// then at the end:
ctx.fill();
}