// grab the canvas element, get the context for API access and // preset some variables var canvas = document.querySelector( 'canvas' ), c = canvas.getContext( '2d' ), mouseX = 0, mouseY = 0, width = 300, height = 300, distx = 0, disty = 0, hw = width / 2, hh = height / 2; // resize the canvas canvas.width = width; canvas.height = height; function draw() { // calculate the distance caused by the offset distx = mouseX - hw; disty = mouseY - hh; c.clearRect( 0, 0, width, height ); // set the colour c.save(); c.translate( hw, hh); c.beginPath() c.strokeStyle = '#fff'; c.moveTo( 0, 0 ); c.lineTo( distx, disty ); c.closePath(); c.stroke(); c.fillStyle = 'lime'; c.beginPath() c.arc( distx, disty, 20 , 0, Math.PI*2, true ); c.closePath(); c.fill(); c.restore(); } // get the mouse position on the canvas (some browser trickery involved) canvas.addEventListener( 'mousemove', function( event ) { if( event.offsetX ){ mouseX = event.offsetX; mouseY = event.offsetY; } else { mouseX = event.pageX - event.target.offsetLeft; mouseY = event.pageY - event.target.offsetTop; } // call the draw function draw(); }, false );
<canvas></canvas>
*{margin:0;padding:0;} canvas{background:#69c;}