0
点赞
收藏
分享

微信扫一扫

polygon.js---多边形52

//建立这样一个对象,每次绘制时可以加入到一个缓存中,以后可以实现拖动等操作
var Point = function (x, y) {
   this.x = x;
   this.y = y;
};

var Polygon = function (centerX, centerY, radius, sides, startAngle, strokeStyle, fillStyle, filled) {
   this.x = centerX;
   this.y = centerY;
   this.radius = radius;
   this.sides = sides;
   this.startAngle = startAngle;
   this.strokeStyle = strokeStyle;
   this.fillStyle = fillStyle;
   this.filled = filled;
};

Polygon.prototype = {
   getPoints: function () {//保存多边形的点的数组,根据多边形的边来绘制的,是一个规则的图形
      var points = [],
          angle = this.startAngle || 0;

      for (var i=0; i < this.sides; ++i) {
         points.push(new Point(this.x + this.radius * Math.sin(angle),
                           this.y - this.radius * Math.cos(angle)));
         angle += 2*Math.PI/this.sides;
      }
      return points;
   },

   createPath: function (context) {//创建一个隐形路径,可以用来实现拖动,碰撞等多个操作,因为它是隐形的,必须调用下面的stroke和fill方法才会可见
      var points = this.getPoints();

      context.beginPath();

      context.moveTo(points[0].x, points[0].y);

      for (var i=1; i < this.sides; ++i) {
         context.lineTo(points[i].x, points[i].y);
      }

      context.closePath();
   },

   stroke: function (context) {
      context.save();
      this.createPath(context);
      context.strokeStyle = this.strokeStyle;
      context.stroke();
      context.restore();
   },

   fill: function (context) {
      context.save();
      this.createPath(context);
      context.fillStyle = this.fillStyle;
      context.fill();
      context.restore();
   },

   move: function (x, y) {//暂时不知道此方法做何用处,这里的x,y是多边形的中间点位置
      this.x = x;
      this.y = y;
   }
};

举报

相关推荐

0 条评论