0

I am trying to get the absolute position of a line based on the canvas's top left corner. However, I can only seem to get back the relative position(coordinates) based on the position of the line when it was originally drawn.

    var line = new Kinetic.Line({
        points: [521, 27, 465, 99],
        stroke: '#ff0000',
        strokeWidth: 10,
        draggable: true
    });

Is there any way to get the absolute coordinates of the line based on the canvas's (0,0) top left coordinates? I know you can get the absolute coordinates of a path, but for what I am trying to do, I would like to use a line. Any help is appreciated and I hope the answer is not that it can't be done.

1 Answers1

2

Assuming your desired reference point on your line is the first x/y in points[], you can get the line's position relative to the top-left canvas corner like this:

  • Save the original XY of that reference point as new properties on the line

  • Listen to the dragmove event and add that original XY back to the current getX/getY

  • Results: position of the line relative to canvas [0,0]

Alternatively, if you wanted the position of your line's bounding box, you must first iterate through each point and fetch the line's top-left most XY.

Here's code and a Fiddle: http://jsfiddle.net/m1erickson/jELRL/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prototype</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>

<style>
body{padding:20px;}
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:350px;
  height:350px;
}
</style>        
<script>
$(function(){

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 350,
        height: 350
    });
    var layer = new Kinetic.Layer();
    stage.add(layer);


    var $results=$("#results");

    var line = new Kinetic.Line({
        points: [121, 27, 165, 99],
        stroke: '#ff0000',
        strokeWidth: 10,
        draggable: true
    });
    var point=line.getPoints()[0];
    line.originalX=point.x;
    line.originalY=point.y;
    line.on("dragmove",function(){
        $results((this.getX()+this.originalX)+"/"+(this.getY()+this.originalY));
    });
    layer.add(line);

    layer.draw();


}); // end $(function(){});

</script>       
</head>

<body>
    <p id="results">Results</p>
    <div id="container"></div>
</body>
</html>
markE
  • 102,905
  • 11
  • 164
  • 176
  • Hey, thanks. I was able to use your answer to find my solution. Turns out for what I was doing, I only really needed to find the absolute position of just one point of the line to use. So your answer regarding a point on the line did the trick. – itsstephyoutrick Nov 25 '13 at 21:05