var canvas, xo, yo, cursor, ctx, offsetAngle, directions; var w = 800; var h = 600; var clickI = 0; 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(); ctx.moveTo( -w * Math.cos( angle ) + x, -w * Math.sin( angle ) + y ); ctx.lineTo( w * Math.cos( angle ) + x, w * Math.sin( angle ) + 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 = Math.sqrt( dx * dx + dy * dy ); var hypAngle = Math.atan2( dy, dx ); // renderAngle( cursorAngle, xo, yo, 'yellow' ); renderAngle( cursorAngle, x, y, 'orange' ); // renderAngle( offsetAngle, x, y, 'cyan' ); ctx.strokeStyle = 'cyan'; // ctx.save(); ctx.beginPath(); ctx.moveTo( xo, yo ); ctx.lineTo( d1 * Math.cos( hypAngle ) + xo, d1 * Math.sin( hypAngle ) + yo ); ctx.moveTo( xo, yo ); ctx.moveTo( xo + 30, yo ); ctx.arc( xo, yo, 30, 0, hypAngle ) ctx.stroke(); var a2 = Math.abs( hypAngle - offsetAngle ); var d2 = Math.abs( d1 * Math.cos( a2 ) ); // render circle measuring the distance ctx.strokeStyle = 'black'; ctx.beginPath(); ctx.arc( xo, yo, d2, 0, Math.PI * 2 ); ctx.stroke(); ctx.restore(); directions.innerText = 'distance = ' + ~~d2 + '. Click again to set origin point'; // var b = x * Math.tan( offsetAngle - Math.PI / 2 ) - y; } function handleClick( event ) { var x = event.pageX; var y = event.pageY; switch ( clickI % 3 ) { case 0 : click0( x, y ); break; case 1 : click1( x, y ); break; case 2 : click2( x, y ); break; } clickI ++; } 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 ); } window.addEventListener( 'DOMContentLoaded', init, false );