Canvas: Continue lineTo path with x fixed - Javascript Canvas

Javascript examples for Canvas:Path

Description

Canvas: Continue lineTo path with x fixed

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <link rel="stylesheet" type="text/css" media="all" href="reset.css"> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){// w  ww .j a va2s  .co  m
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var x0=25;
    var y0=50;
    var x1=150;
    var y1=150;
    ctx.beginPath();
    ctx.moveTo(x0,y0);
    ctx.lineTo(x1,y1);
    ctx.strokeStyle='blue';
    ctx.stroke();
    var newY=extendToX(200,x0,y0,x1,y1);
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(200,newY);
    ctx.strokeStyle='red';
    ctx.stroke();
    function extendToX(desiredX,x0,y0,x1,y1){
        var m=(y0-y1)/(x0-x1);
        var b=y1-(m*x1);
        return(m*desiredX+b);
    }
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <h4>Use slope-intercept formula to extend line</h4> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials