0

我在舞台上有一个带有多个点的 Kinetic.Polygon 对象。我正在尝试计算多边形边界的尺寸和尺寸。关于如何做到这一点的任何想法?

4

1 回答 1

1

您可以通过枚举多边形的点并获取最小值和最大值来获取此信息。

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;

这是代码和小提琴: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>
于 2013-08-24T03:53:59.670 回答