user3651476
user3651476

Reputation: 171

Find the length of line in canvas

I want to find the length of a line i have drawn inside a canvas. I already can draw the line inside the canvas but badly need to find its length.

Find this link, but i want to know what are the things needed to have a precise measurement. Thanks.

Link i found

So far this is my code:

$("#myCanvas").bind('mousemove', function(e){   
                    var totalOffsetX = 0;
                    var totalOffsetY = 0;       
                    var currentElement = this;

                    do{
                        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
                        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
                    }
                    while(currentElement = currentElement.offsetParent)

                    endX= e.pageX - totalOffsetX;
                    endY = e.pageY - totalOffsetY;

                    drawLine(startX, startY, endX, endY);
                });             
            }).mouseup(function(data){
                if(trigger = "1"){
                    $('.draggable').draggable( "disable" );
                }else{
                    $('.draggable').draggable("enable");
                }   
                $(this).unbind('mousemove');
            });

Thanks in advance..

Upvotes: 3

Views: 6614

Answers (3)

Simon
Simon

Reputation: 21

use distance formula distance as distance= √((x2– x1)2+ (y2– y1)2)

i.e in JS

distance: function (x1, y1, x2, y2) {
  let dx = x2 - x1;
  let dy = y2 - y1;

  dx = dx * dx;
  dy = dy * dy;

  return Math.sqrt( dx + dy );
},

Upvotes: 1

yckart
yckart

Reputation: 33378

Since ECMA-262, there's a Math.hypot method, which returns the square root of the sum of squares of its arguments.

Math.hypot(v1, v2) === Math.sqrt(v1*v1 + v2*v2)

You could create a simple helper function:

function lineDistance(p1, p2) {
  return Math.hypot(p2.x - p1.x, p2.y - p1.y)
}

Upvotes: 6

Otto Mao
Otto Mao

Reputation: 31

You may this formula to calculate the distance between two points with startX,startY,endX,endY.

function lineDistance( point1, point2 ){
    var xs = 0;
    var ys = 0;

    xs = point2.x - point1.x;
    xs = xs * xs;

    ys = point2.y - point1.y;
    ys = ys * ys;

    return Math.sqrt( xs + ys );
}

Upvotes: 3

Related Questions