日期:2014-05-16  浏览次数:20801 次

HTML5 Canvas画标准的五星红旗(中国国旗)
国旗的标准画法图。



代码如下:
<!DOCTYPE html>
<html>
<head>
  <meta charset="gbk">
  <title>中国标准国旗</title>
</head>
<body>
  <canvas id="canvas" width="600" height="400"></canvas>
  <script>
  /**
    使用HTML5绘制标准五星红旗
  */
var canvas = document.getElementById("canvas");
  var context = canvas.getContext('2d');
  var width=canvas.width;
  var height=width*2/3;
  var w=width/30;//小网格的宽
  context.fillStyle="red";
  context.fillRect(0,0,width,height);
  var maxR = 0.15, minR = 0.05;//
  var maxX = 0.25, maxY = 0.25;//大五星的位置
  var minX = [0.50, 0.60, 0.60, 0.50];
  var minY = [0.10, 0.20, 0.35, 0.45];
  // 画大☆
  var ox = height * maxX, oy = height * maxY;
  create5star(context,ox,oy,height * maxR,"#ff0",0);//绘制五角星
  // 画小★
  for (var idx = 0; idx < 4; idx++) {
    var  sx = minX[idx] * height, sy = minY[idx] * height;
    var  theta = Math.atan((oy - sy)/(ox - sx));
    create5star(context,sx, sy, height * minR, "#ff0",-Math.PI/2+theta);
   }
  //辅助线
  context.moveTo(0,height/2)
  context.lineTo(width,height/2);
  context.stroke();
  context.moveTo(width/2,0);
  context.lineTo(width/2,height);
  context.stroke();
  //画网格,竖线
   for(var j=0;j< 15;j++){
      context.moveTo(j*w,0);
      context.lineTo(j*w,height/2);
      context.stroke();
   }
   //画网格,横线
    for(var j=0;j< 10;j++){
      context.moveTo(0,j*w);
      context.lineTo(width/2,j*w);
      context.stroke();
   }
    //画大圆
    context.beginPath();
    context.arc(ox,oy,maxR*height,0,Math.PI*2,false);
    context.closePath();
    context.stroke();
    // 画小圆
    for (var idx = 0; idx < 4; idx++) {
     context.beginPath();
     var  sx = minX[idx] * height, sy = minY[idx] * height;
     context.arc(sx, sy, height * minR,0,Math.PI*2,false);
     context.closePath();
     context.stroke();
    }  
    //大圆中心与小圆中心连接线
    for (var idx = 0; idx < 4; idx++) {
     context.moveTo(ox,oy);
     var  sx = minX[idx] * height, sy = minY[idx] * height;
     context.lineTo(sx, sy);
     context.stroke();
    }  
   //绘制五角星
  /**
   * 创建一个五角星形状. 该五角星的中心坐标为(sx,sy),中心到顶点的距离为radius,rotate=0时一个顶点在对称轴上
   * rotate:绕对称轴旋转rotate弧度
   */
  function create5star(context,sx,sy,radius,color,rotato){
    context.save();
    context.fillStyle=color;
    context.translate(sx,sy);//移动坐标原点
    context.rotate(Math.PI+rotato);//旋转
    context.beginPath();//创建路径
    var x = Math.sin(0);
    var y= Math.cos(0);
    var dig = Math.PI/5 *4;
    for(var i = 0;i< 5;i++){//画五角星的五条边
     var x = Math.sin(i*dig);
     var y = Math.cos(i*dig);
     context.lineTo(x*radius,y*radius);
   } 
   context.closePath();
   context.stroke();
   context.fill();
   context.restore();
  }  


</script>
</body>
</html>
观看效果与源码下载:http://www.108js.com/article/article7/70179.html?id=920