Q:

detect close path in canvas

Hi I'm searching to find a way to close path with javascript.
I can draw a series of straight lines by clicking on the canvas but I want that when the line are closed the object create takes a grey background.
Like in this example when you close the wall the room appears

var needFirstPoint = true;

function drawNextLine(ctx, x, y) {
    if (needFirstPoint) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(x, y);
        needFirstPoint = false;
    }
    else {
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}

$(document).ready(function(){
    var canvas = $('#myCanvas').get(0);
    if (!canvas.getContext) { return; }
    var ctx = canvas.getContext('2d');
    
    $('#myCanvas').on('click', function(e){
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        drawNextLine(ctx, x, y);
    });
});
canvas {
    border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="600" height="600"></canvas>

I don't know how to detect a close path that could form an object

A:

EDIT: There is a simpler solution. Remember the position of the first click and check if any of the subsequent clicks are nearby.
https://codepen.io/anon/pen/pQLwGK
var startX = -1, startY = -1; 

function dist(x0,y0,x1,y1)
{
  return Math.sqrt( Math.pow(x1-x0,2) + Math.pow(y1-y0,2));
}

$(document).ready(function()
{
    var canvas = $('#myCanvas').get(0);
    if (!canvas.getContext) { return; }
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = '#f00';
    ctx.beginPath();
    $('#myCanvas').on('click', function(e)
    {
        console.log('click');
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        if (startX === -1)
        {
          console.log('start position is set to ',x ,y);
          startX = x;
          startY = y;
          ctx.moveTo(x,y);
        }
        else
        {
          // checking if a click is within 20px of the starting point
          if (dist(startX, startY,x,y ) < 20)
          {
             // assume that polygon is closed
             ctx.lineTo(startX,startY);
             ctx.fill();
             console.log('fill');
          }
          else
          {
             ctx.lineTo(x,y);
          }
          ctx.stroke();
        }
    });
});

