vutran
vutran

Reputation: 887

Getting the position and dimensions of a Polygon

I have a Kinetic.Polygon object on the stage with multiple points. I'm trying to calculate the dimensions of the polygon's bounds and the dimensions. Any ideas on how to do this?

Upvotes: 0

Views: 339

Answers (1)

markE
markE

Reputation: 105035

You can get this info by enumerating through the polygon's points and getting mins and maxes.

var minX=minY=1000000;
var maxX=maxY=-1000000;

var points=myPolygon.getPoints();

for(var i=0;i<points.length;i++){
    var p=points[i];
    if(p.x<minX){minX=p.x;}
    if(p.y<minY){minY=p.y;}
    if(p.x>maxX){maxX=p.x;}
    if(p.y>maxY){maxY=p.y;}
}

var width=maxX-minX;
var height=maxY-minY;

var boundsLeft=minX+myPolygon.getX();
var boundsRight=boundsLeft+width;
var boundsTop=minY+myPolygon.getY();
var boundsBottom=boundsTop+height;

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/FghXD/

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.6.0.min.js"></script>
    <script defer="defer">
      var stage = new Kinetic.Stage({
        container: 'container',
        width: 778,
        height: 600
      });

      var layer = new Kinetic.Layer();

      var poly = new Kinetic.Polygon({
        x:200,
        y:20,
        points: [73, 192, 73, 160, 340, 23, 500, 109, 499, 139, 342, 93],
        fill: '#00D2FF',
        stroke: 'black',
        strokeWidth: 5,
        draggable:true
      });

      poly.on("dragend",function(){
          calc();
      });

      function calc(){
          var minX=minY=1000000;
          var maxX=maxY=-1000000;

          var points=poly.getPoints();

          for(var i=0;i<points.length;i++){
              var p=points[i];
              if(p.x<minX){minX=p.x;}
              if(p.y<minY){minY=p.y;}
              if(p.x>maxX){maxX=p.x;}
              if(p.y>maxY){maxY=p.y;}
          }

          var width=maxX-minX;
          var height=maxY-minY;

          var boundsLeft=minX+poly.getX();
          var boundsRight=boundsLeft+width;
          var boundsTop=minY+poly.getY();
          var boundsBottom=boundsTop+height;

          alert("w/h: "+width+"/"+height+" -- bounds(t/l-b/r): "+boundsTop+"/"+boundsLeft+"-"+boundsBottom+"/"+boundsRight);
      }

      // add the shape to the layer
      layer.add(poly);

      // add the layer to the stage
      stage.add(layer);
    </script>
  </body>
</html>

Upvotes: 1

Related Questions