HTML5自学笔记[ 24 ]canvas绘图之星空草地

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 
 7     <style>
 8         body{ background:#fff;}
 9         div{ width:800px; height:600px; margin:0 auto;}
10         canvas{ background:#000;}
11     </style>
12     <script src="drawstars.js"></script>
13 </head>
14 <body>
15     <div>
16         <canvas id="canvas1" width="800" height="600"></canvas>
17     </div>
18 </body>
19 </html>
 1 window.onload = function(){
 2 
 3     var cvs = document.getElementById('canvas1');
 4     var cxt = cvs.getContext('2d');
 5     var R;
 6 
 7     var lineGrad = cxt.createRadialGradient(cvs.width/2,cvs.height,0,cvs.width/2,cvs.height,cvs.width);
 8     lineGrad.addColorStop(0,'#191970');
 9     lineGrad.addColorStop(1,'#000');
10     cxt.fillStyle = lineGrad;
11     cxt.fillRect(0,0,cvs.width,cvs.height);
12 
13     //星星
14     for(var i=0;i<100;i++){
15         R = 2+5*Math.random();
16         drawStar(cxt,cvs.width*Math.random(),cvs.height*0.7*Math.random(),R,'#FFFF00');
17     }
18 
19     //月亮
20     drawMoon(cxt,600,100,40,3,30,'#FFF68F')
21 
22     //草地
23     cxt.save();
24 
25     cxt.beginPath();
26     cxt.moveTo(0,400);
27     cxt.bezierCurveTo(200,300,500,500,800,450);
28     cxt.lineTo(800,600);
29     cxt.lineTo(0,800);
30     cxt.closePath();
31 
32     cxt.fillStyle = 'green';
33     cxt.fill();
34 
35     cxt.restore();
36 
37 
38 
39 }
40 
41 function drawMoon(cxt,x,y,r,d,rot,fillColor){
42     cxt.save();
43 
44     cxt.translate(x,y);
45     cxt.scale(r,r);
46     cxt.rotate(rot*Math.PI/180);
47 
48     moonPath(cxt,d);
49 
50     cxt.fillStyle = 'yellow' || fillColor;
51 
52     cxt.fill();
53 
54     cxt.restore();
55 }
56 
57 function moonPath(cxt,d){
58     cxt.beginPath();
59     cxt.arc(0,0,1,0.5*Math.PI,1.5*Math.PI,true);
60     cxt.moveTo(0,-1);
61     cxt.arcTo(d,0,0,1,Math.sqrt(1+d*d)/d);
62 }
63 
64 function drawStar(cxt,x,y,R,fillColor){
65     cxt.save();
66 
67 
68     cxt.translate(x,y);
69     cxt.rotate(360*Math.random()*Math.PI/180);
70     cxt.scale(R,R);
71 
72     starPath(cxt);
73 
74     cxt.fillStyle = fillColor;
75 
76     cxt.fill();
77     cxt.restore();
78 
79 
80 
81 }
82 function starPath(cxt){
83     cxt.beginPath();
84     for(var i=0;i<5;i++){
85         cxt.lineTo(Math.cos((18+72*i)*Math.PI/180),-Math.sin((18+72*i)*Math.PI/180));
86         cxt.lineTo(Math.cos((54+72*i)*Math.PI/180)*0.5,-Math.sin((54+72*i)*Math.PI/180)*0.5);
87     }
88     cxt.closePath();
89 }

该实例来自慕课网的学习,感兴趣的朋友可以去学习一下哦~

HTML5自学笔记[ 24 ]canvas绘图之星空草地_第1张图片

你可能感兴趣的:(HTML5自学笔记[ 24 ]canvas绘图之星空草地)