Monday 7 August 2017

Finding intersection between two lines with HTML5 and Javascript

This article will look at detecting intersection of two lines using Javascript and using HTML 5 Canvas to display the two lines.

A plunk is available here:
Plunk - Intersection of two lines

















We continue from the last article and add a LineIntersection function and add prototype functions. This "class" will help us find the intersection points. The code is as follows:

   function LineIntersection (config){
        this.m1 = config.m1;
        this.b1 = config.b1;
        this.m2 = config.m2;    
        this.b2 = config.b2;

        this.error = 0;
        this.marginOfError = 0.01;
        this.iterations = 0;
        this.maxIterations = 200;
   
      }

      LineIntersection.prototype.PrintData = function() {
        console.clear();
        console.log("m1: " + this.m1 + " b1: " + this.b1 + " m2: " + this.m2 + " b2: " + this.b2);
      }

      LineIntersection.prototype.GetGuess = function(guess){
        var newguess = ((this.b2 - this.b1) / (this.m1 - this.m2) + guess) / 2;
        return newguess;
      }

      LineIntersection.prototype.Y1 = function (guess){
        return this.m1 * guess + this.b1;
      }

      LineIntersection.prototype.Y2 = function (guess){
        return this.m2 * guess + this.b2;
      }

      LineIntersection.prototype.DeltaY = function (guess){
        return Math.abs(this.Y1(guess) - this.Y2(guess));
      }

      LineIntersection.prototype.FindIntersection = function(){

        this.iterations = 0;
       
        if (this.m1 == this.m2)
        {
          alert("The two lines are parallel!");
          return { x: "Infinity", y: "Infinity"};
        }

        guess = Math.floor(Math.random() * 10 + 1);

        do {
         guess = this.GetGuess(guess);

         this.error = this.DeltaY(guess);

         if (this.iterations > this.maxIterations){
          break;

          this.iterations = this.iterations + 1;
         }

        }
        while (this.error > this.marginOfError);

        return { x: guess.toFixed(2), y: this.Y1(guess).toFixed(2) }

      } //function LineIntersection 



The intersection point is then calculated using the code in the following jQuery button click event handler:

   $("#btnIntercept").click(function(){
          var m1,b1,m2,b2 = 0;

        m1 = parseFloat($("#m1").val());
        b1 = parseFloat($("#b1").val());
        m2 = parseFloat($("#m2").val());
        b2 = parseFloat($("#b2").val());
       
        var myGraph = new Graph({
         canvasId: 'Graph',
         minX: -10,
         minY: -10,
         maxX: 10,
         maxY: 10,
         unitsPerTick: 1
        });      

        myGraph.drawLine(m1, b1, 'blue', 3);

        myGraph.drawLine(m2, b2, 'red', 4);

        var lineIntersect = new LineIntersection({
          m1: m1,
          b1: b1,
          m2: m2,
          b2: b2
        });

        lineIntersect.PrintData();

        var intersect = lineIntersect.FindIntersection();
        console.log(intersect);
        console.log(intersect.x);

        myGraph.drawRect(intersect.x, intersect.y, 0.5, 0.5);

        $("#detailsInfo").append("Intersection point: " + " X: " + intersect.x + " Y: " + intersect.y);


To plot a dot where the calculated intersection point the following code is used:
        Graph.prototype.drawRect = function (x, y, width, height){
        var context = this.context; 
        this.transformContext();
        context.strokeStyle = 'green';
        context.fillRect(x - (width/2), y - (height/2), width, height);
      }
To move from object space coordinates to display coordinates we make use of the following helper function:

        Graph.prototype.transformContext = function() {
        var context = this.context;

        // move context to center of canvas
        this.context.translate(this.centerX, this.centerY);

        /*
         * stretch grid to fit the canvas window, and
         * invert the y scale so that that increments
         * as you move upwards
         */
        context.scale(this.scaleX, -this.scaleY);
      };


Share this article on LinkedIn.

1 comment:

  1. Interesting blog about finding intersection between two points which attracted me more.Spend a worthful time.keep updating more.
    SEO Company in India

    ReplyDelete