get offset distance
Given an offset angle and a point, what is the distance of that point, perpendicular to the offset angle? See http://www.flickr.com/photos/nemoorange/6684665563/ for this geometry in use
by John Schulz
HTML
<h1>get offset distance</h1>
<p id="directions"></p>
<canvas></canvas>
CSS
body {
margin: 0;
padding: 0;
}
canvas {
position: absolute;
left: 0;
top: 0;
}
JavaScript
var canvas, xo, yo, cursor, ctx, offsetAngle, directions;
var w = 800;
var h = 600;
var clickI = 0;
var clicks = [click0, click1, click2];
window.addEventListener( 'DOMContentLoaded', init, false );
function init() {
directions = document.getElementById('directions');
directions.innerText = 'Click to set origin point';
canvas = document.getElementsByTagName('canvas')[0];
canvas.width = w;
canvas.height = h;
ctx = canvas.getContext('2d');
canvas.addEventListener( 'click', handleClick, false );
}
function handleClick( event ) {
var x = event.pageX;
var y = event.pageY;
var i = clickI++ % clicks.length;
clicks[ i ]( x, y );
}
function click0( x, y ) {
ctx.clearRect( 0, 0, 800, 600 );
// render crosshairs and origin point
ctx.strokeStyle = '#DDD';
ctx.beginPath();
ctx.moveTo( 0, y );
ctx.lineTo( w, y );
ctx.moveTo( x, 0 );
ctx.lineTo( x, h );
ctx.stroke();
ctx.strokeStyle = 'blue';
ctx.beginPath();
ctx.arc( x, y, 10, 0, Math.PI * 2 );
ctx.stroke();
// save origin point
xo = x;
yo = y;
originPoint = {
x: x,
y: y
};
directions.innerText = 'Click again to set offset angle';
}
function renderAngle( angle, x, y, color ) {
ctx.strokeStyle = color;
ctx.beginPath();
var xx = w * Math.cos( angle );
var yy = w * Math.sin( angle );
ctx.moveTo( -xx + x, -yy + y );
ctx.lineTo( xx + x, yy + y );
ctx.stroke();
}
function click1( x, y ) {
// render offset angle
// var m = ( x - xo ) / ( y - yo );
offsetAngle = Math.atan2( y - yo, x - xo );
renderAngle( offsetAngle, xo, yo, 'green' );
ctx.strokeStyle = '#6C6';
ctx.beginPath();
ctx.arc( xo, yo, 20, 0, offsetAngle );
ctx.stroke();
directions.innerText = 'Click again to set cursor point';
}
function click2( x, y ) {
// render dot
ctx.fillRect( x - 2, y - 2, 4, 4 );
var cursorAngle = offsetAngle - Math.PI / 2;
var dx = x - xo;
var dy = y - yo;
var d1 =...