Line detection

via Kevin Mehall: http://blog.kevinmehall.net/2009/line-and-shape-recognition

HTML

<canvas id='canvas'>

</canvas> 

<div id='help'>Click and drag to draw lines
	<div>(Also try closed polygons and rectangles)</div></div>

<button id='clear'>Clear</button>

<a id='moreinfo' href='http://blog.kevinmehall.net/2009/line-and-shape-recognition'>About</a>
<a id='larger' href='http://labs.kevinmehall.net/line-and-shape-recognition' target='_top'>Full Page</a>
</div>

CSS

* {
	padding: 0;
	margin:0;

}

#canvas{
	cursor: crosshair;
	position: absolute;
	z-index: 10;
}

#clear{
	position: absolute;
	bottom: 5px;
	right: 5px;
	z-index: 100;
}

#help{
	z-index: 1;
	position: absolute;
	color: #888;
	font-size: 23px;
	top: 50%;
	left: 50%;
	text-align: center;
	width: 400px;
	height: 100px;
}

#help  > div{
	font-size: 15px;
}

#moreinfo, #larger{
	position: absolute;
	left: 3px;
	bottom: 3px;
	font-size: 12px;
	z-index: 20;
}

#larger{
	display: none;
}

JavaScript

canvas=document.getElementById('canvas')

canvas.width=window.innerWidth
canvas.height=window.innerHeight

$('#help')	.css('left', (window.innerWidth - $('#help').width())/2+'px')
			.css('top', (window.innerHeight - $('#help').height())/2+'px')
			

if (window.location.search=='?embed'){
	$('#moreinfo').hide()
	$('#larger').show()
}

c=canvas.getContext('2d')

function getpos(e){
	var offset=$(canvas).offset()
	return {
		x:e.pageX-offset.left,
		y:e.pageY-offset.top,
	}
}

TAN_HALF_PI=Math.tan(Math.PI/2)

function direction(d){
	var horiz=(Math.abs(d.x)>Math.abs(d.y))
	if (horiz){
		if (d.x<0) return 0;
		return 1;
	}else{
		if (d.y<0) return 2;
		return 3;
	}
}

colors=['rgba(255,0,0,0.5)',
			  'rgba(0,255,0,0.5)',
			  'rgba(0,0,255,0.5)',
			  'rgba(200,200,0,0.5)',
			  ]

function vector(x, y){
	return {
		x:x, 
		y:y,
	}
}
			  
function delta(a, b){
	return vector(a.x - b.x, a.y - b.y)
}

function angle(d){
	return Math.atan((1.0*d.y)/d.x)
}

function angle_between(a, b){
	return Math.acos((a.x*b.x + a.y*b.y)/(len(a)*len(b)))
}

function len(v){
	return Math.sqrt(v.x*v.x + v.y*v.y)
}

function unit(c){
	var l=len(c)
	return vector(c.x/len(c), c.y/len(c))
}

function scale(c, f){
	return vector(c.x*f, c.y*f)
}

function add(a, b){
	return vector(a.x+b.x, a.y+b.y)
}

function rotate(v, a){
	return vector(	v.x*Math.cos(a) - v.y*Math.sin(a),
					v.x*Math.sin(a) + v.y*Math.cos(a))
}

function average(l){
	var x=0
	var y=0
	for (var i=0; i<l.length; i++){x+=l[i].x; y+=l[i].y}
	return vector(x/l.length, y/l.length)
}

$(canvas).mousedown(function(e){
	$("#help").fadeOut(200)
	prev=getpos(e)
	line=[prev]


	$(canvas).mousemove(function(e){
		pos=getpos(e)
		 
 		c.beginPath();
  		c.moveTo(prev.x, prev.y);
  		c.lineTo(pos.x, pos.y);
  		c.stroke()
  		
	  	prev=pos
	  	line.push(pos)
		
	})
	
	c.strokeStyle="rgba(0,0,0,0.2)"
	
	
	$(canvas).mouseup(function(){
		$(canvas).unbind('mousemove').unbind('mouseup')
		corners=[line[0]]
		var n=0
		var t=0
		var...