var canvas=$('#canvas')[0], context=canvas.getContext('2d'), eraseAllButton = $('#eraseAllButton'), strokeStyleSelect=$('#strokeStyleSelect'), guidewireCheckbox= $('#guidewireCheckbox'), drawingSurfaceImageData, mousedown={}, rubberbandRect={}, dragging=false, guidewires= guidewireCheckbox.prop('checked'); function windowToCanvas(x,y){ var bbox = canvas.getBoundingClientRect(); return { x: x- bbox.left * ( canvas.width / bbox.width ), y: y- bbox.top * ( canvas.height / bbox.height ) }; } function saveDrawingSurface(){ drawingSurfaceImageData = context.getImageData( 0,0, canvas.width, canvas.height ); } function restoreDrawingSurface(){ context.putImageData( drawingSurfaceImageData, 0,0 ); } function updateRubberBandRectangle( loc ){ rubberbandRect.width = Math.abs( loc.x - mousedown.x ); rubberbandRect.height = Math.abs( loc.y - mousedown.y ); if( loc.x > mousedown.x ) rubberbandRect.left = mousedown.x; else rubberbandRect.left = loc.x; if( loc.y > mousedown.y ) rubberbandRect.top = mousedown.y; else rubberbandRect.top = loc.y; } function drawRubberBandShape( loc ){ context.beginPath(); context.moveTo( mousedown.x, mousedown.y ); context.lineTo( loc.x, loc.y ); context.stroke; } function updateRubberband( loc ){ updateRubberBandRectangle( loc ); drawRubberBandShape( loc ); } function drawHorizontalLine( y ){ context.beginPath(); context.moveTo(0, y+0.5); context.lineTo( canvas.width, y+ 0.5 ); context.stroke(); } function drawVerticalLine( x ){ context.beginPath(); context.moveTo(x+0.5, 0); context.lineTo( x+ 0.5 , canvas.height ); context.stroke(); } function drawGuideWires( x, y ){ context.save(); context.strokeStyle = 'rgba( 0,0,230, 0.4 )'; context.lineWidth = 0.5; drawVerticalLine( x ); drawHorizontalLine( y ); context.restore(); } canvas.onmousedown = function(e){ var loc = windowToCanvas( e.clientX, e.clientY ); e.preventDefault(); saveDrawingSurface(); mousedown.x = loc.x; mousedown.y = loc.y; dragging = true; }; canvas.onmousemove = function(e){ var loc; if( dragging ){ e.preventDefault(); loc = windowToCanvas( e.clientX, e.clientY ); restoreDrawingSurface(); updateRubberband( loc ); if( guidewires ){ drawGuideWires( loc.x, loc.y ); } } }; canvas.onmouseup = function(e){ loc = windowToCanvas( e.clientX, e.clientY ); restoreDrawingSurface(); updateRubberband( loc ); dragging = false; }; eraseAllButton.click( function(){ context.clearRect( 0,0, canvas.width, canvas.height ); saveDrawingSurface(); } ); strokeStyleSelect.change( function(){ context.strokeStyle = strokeStyleSelect.val(); } ); guidewireCheckbox.change( function(){ guidewires = guidewireCheckbox.val(); } ); context.strokeStyle = strokeStyleSelect.val();