码迷,mamicode.com
首页 > Web开发 > 详细

html5 canvas画五角星(美国队长)

时间:2016-11-23 22:47:15      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:tco   com   png   var   nload   math   load   alt   doctype   

画一波五角星: 美国队长图标

原理:  (1)根据五角星的顶点,外顶点5个,内顶点5个,分成内外圆

             (2)由三角函数可表示出每个顶点的位置

              (3)利用canvas的lineTo()接口画图

上代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Captain America</title>
 7     <style type="text/css">
 8     #canvas {
 9         display: block;
10         margin: 50px auto;
11     }
12     </style>
13 </head>
14 
15 <body>
16     <canvas id="canvas"></canvas>
17     <script>
18     window.onload = function() {
19         var canvas = document.getElementById("canvas");
20         canvas.width = 800;
21         canvas.height = 600;
22 
23         var context = canvas.getContext("2d");
24         // 四个圆
25         drawArc(context, 300, 300, 120, 0, Math.PI * 2, false, "#dd5870");
26         drawArc(context, 300, 300, 100, 0, Math.PI * 2, false, "#e0dedf");
27         drawArc(context, 300, 300, 80, 0, Math.PI * 2, false, "#dd5870");
28         drawArc(context, 300, 300, 60, 0, Math.PI * 2, false, "#2773d3");
29         drawStar(context, 20, 60, 300, 300, 0, "#dedce1"); // 五角星  
30     }
31 
32     function drawStar(ctx, r, R, x, y, changeDeg, fillColor) {
33         //绘制星星的路径,changeDeg:表示五角星旋转的角度
34         ctx.beginPath(); //开始路径  
35         for (var i = 0; i < 5; i++) {
36             ctx.lineTo(Math.cos((18 + i * 72 - changeDeg) / 180 * Math.PI) * R + x, -Math.sin((18 + i * 72 - changeDeg) / 180 * Math.PI) * R + y);
37             ctx.lineTo(Math.cos((54 + i * 72 - changeDeg) / 180 * Math.PI) * r + x, -Math.sin((54 + i * 72 - changeDeg) / 180 * Math.PI) * r + y);
38         }
39         ctx.closePath() //结束路径  
40         ctx.fillStyle = fillColor;
41         ctx.fill();
42     }
43 
44     function drawArc(ctx, x, y, r, stratAngel, endAngel, flag, fillColor) {
45         ctx.beginPath();
46         ctx.arc(x, y, r, stratAngel, endAngel, flag);
47         ctx.fillStyle = fillColor;
48         ctx.fill();
49         ctx.closePath();
50     }
51     </script>
52 </body>
53 </html>

结果:

技术分享

 

html5 canvas画五角星(美国队长)

标签:tco   com   png   var   nload   math   load   alt   doctype   

原文地址:http://www.cnblogs.com/it-xiaojun/p/6095554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!