canvas繪製五角星程式碼例項

admin發表於2017-02-23
分享一段程式碼例項,它實現了利用canvas繪製五角星的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 600;
var ctx = canvas.getContext("2d");
var num = 0;
var timer = setInterval(function() {
  if (num < 36) {
    num++;
    var rot = Math.random() * 30 + 10;
    var x = Math.cos(num * Math.PI / 180 * 10 + 90) * 180 + 200;
    var y = Math.sin(num * Math.PI / 180 * 10 + 90) * 180 + 300;
    var R = Math.ceil(Math.random() * 255);
    var G = Math.ceil(Math.random() * 255);
    var B = Math.ceil(Math.random() * 255);
    var color = "#" + R.toString(16) + "" + G.toString(16) + "" + B.toString(16);
    draw(ctx, 18, rot, x, y, {
      "strokeStyle": color,
      "lineWidth": "1",
      "fillStyle": color,
      "run": function(o) {
        o.fill();
      }
 
    })
 
  } else {
    clearInterval(timer);
  }
 
}, 1000 / 60)
 
function draw(ctx, width, rot, dy, dx, options) {
  if (!width) return false;
  var dy = dy || 0,
    dx = dx || 0,
    rot = rot || 0;
  ctx.beginPath();
  for (var i = 0; i < 5; i++) {
    var deg1x = Math.cos((18 + i * 72) * Math.PI / 180 - rot) * width + dx;
    var deg1y = -Math.sin((18 + i * 72) * Math.PI / 180 - rot) * width + dy;
    var deg2x = Math.cos((54 + i * 72) * Math.PI / 180 - rot) * width / 2 + dx;
    var deg2y = -Math.sin((54 + i * 72) * Math.PI / 180 - rot) * width / 2 + dy;
    ctx.lineTo(deg1x, deg1y);
    ctx.lineTo(deg2x, deg2y);
  }
  if (options && typeof options == "object") {
    for (var i in options) {
      if (i != "run") {
        if (typeof options<i> == "string") {
          ctx<i> = options<i>;
        }
      } else if (typeof options<i> == "function") {
        options.run(ctx);
      }
    }
  }
  ctx.closePath();
  ctx.stroke();
}
</script>
</body>
</html>

相關文章