美文网首页程序员
canvas画多边形

canvas画多边形

作者: infi_ | 来源:发表于2018-02-27 15:15 被阅读0次

效果如图


由于canvas只提供了画矩形和圆形的方法,
所以涉及到多边形的话,只能自己写方法
其中涉及到 三角函数的API 比如
Math.PI圆周率
Math.sin
Math.cos
这俩就不多介绍了 sin cos 中学学的
大致思路就是只要有中心点 半径 就可以想画几边形就画几边形,
废话不多说,上代码
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

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=[];
     var angle=this.startAngle||0;
     for(var i=0;i<this.sides;i++){
         points.push(new Point(this.x+this.radius*Math.cos(angle),this.y-this.radius*Math.sin(angle)))
         angle+=2*Math.PI/this.sides

     }
    return points

   },
   createPath:function(){
      var points=this.getPoints()
      context.beginPath()
      context.moveTo(points[0].x,points[0].y);
      for(var i=1;i<points.length;i++){
          context.lineTo(points[i].x,points[i].y)
      }
      context.closePath()
   },
   stroke:function(){
       context.save()
       this.createPath()
       context.strokeStyle=this.strokeStyle;
       context.stroke();
       context.restore();
   },
   fill:function(){
      context.save();
      context.fillStyle=this.fillStyle;
      this.createPath()
      context.fill()
      context.restore()

   },

   move: function (x, y) {
          this.x = x;
           this.y = y;
    }

}
var test1=new Polygon(50,50,30,8,0,"red","red")
test1.stroke()

var test2=new Polygon(150,150,30,4,0,"red","red")
test2.fill()

相关文章

网友评论

    本文标题:canvas画多边形

    本文链接:https://www.haomeiwen.com/subject/uscmxftx.html