title: Canvas - How to find a point on line from a distance
body: <p>I've been working on this game that can move a gun towards where the cursor is. However, all I've got to is this:</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Block Shooter&lt;/title&gt;
      &lt;/head&gt;
      &lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"&gt;&lt;/script&gt;
      &lt;body&gt;
          &lt;center&gt;
              &lt;canvas id="canvas" width="1200" height="600" style="border: 1px solid black"&gt;&lt;/canvas&gt;
              &lt;script&gt;
              // Variables
  
              var canvas = document.getElementById("canvas");
              var ctx = canvas.getContext("2d");
              var start = false;
              var gunWidth = 80;
              var gunLength = 150;
  
              $("#canvas").mousemove((event) =&gt; {
                  ctx.clearRect(0, 0, canvas.width, canvas.height)
                  ctx.beginPath();
                  ctx.lineWidth = gunWidth;
                  ctx.strokeStyle = "black";
                  //get dimensions of canvas. 
                  var dimensions=event.target.getBoundingClientRect();
                  var middle=dimensions.left+(dimensions.width/2)
                  ctx.moveTo(canvas.width / 2, canvas.height);
                  //get mousex relative to canvas
                  var mousex=event.offsetX
                  //get mousey relative to canvas 
                  var mousey=event.offsetY
  
                  var ydistance=mousey;
                  var xdistance=mousex-middle
                  //distance formula 
                  var distance=Math.sqrt((xdistance*xdistance)+(ydistance*ydistance))
  
                  var gunlength=200;
                  var drawx=(gunlength*(xdistance/distance))+middle
                  var drawy=gunlength*(ydistance/distance)
  
                  ctx.lineTo(drawx, drawy);
  
                  ctx.stroke();
                  ctx.closePath();
  
              })
  
              &lt;/script&gt;
          &lt;/center&gt;
      &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>Now, somehow it's not pointing correctly and stops moving. Is there a solution for this? Please provide an example. Thanks!</p>