<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> body{ background:#fff;} div{ width:800px; height:600px; margin:0 auto;} canvas{ background:#000;} </style> <script src="drawstars.js"></script> </head> <body> <div> <canvas id="canvas1" width="800" height="600"></canvas> </div> </body> </html>
window.onload = function(){ var cvs = document.getElementById('canvas1'); var cxt = cvs.getContext('2d'); var R; var lineGrad = cxt.createRadialGradient(cvs.width/2,cvs.height,0,cvs.width/2,cvs.height,cvs.width); lineGrad.addColorStop(0,'#191970'); lineGrad.addColorStop(1,'#000'); cxt.fillStyle = lineGrad; cxt.fillRect(0,0,cvs.width,cvs.height); //星星 for(var i=0;i<100;i++){ R = 2+5*Math.random(); drawStar(cxt,cvs.width*Math.random(),cvs.height*0.7*Math.random(),R,'#FFFF00'); } //月亮 drawMoon(cxt,600,100,40,3,30,'#FFF68F') //草地 cxt.save(); cxt.beginPath(); cxt.moveTo(0,400); cxt.bezierCurveTo(200,300,500,500,800,450); cxt.lineTo(800,600); cxt.lineTo(0,800); cxt.closePath(); cxt.fillStyle = 'green'; cxt.fill(); cxt.restore(); } function drawMoon(cxt,x,y,r,d,rot,fillColor){ cxt.save(); cxt.translate(x,y); cxt.scale(r,r); cxt.rotate(rot*Math.PI/180); moonPath(cxt,d); cxt.fillStyle = 'yellow' || fillColor; cxt.fill(); cxt.restore(); } function moonPath(cxt,d){ cxt.beginPath(); cxt.arc(0,0,1,0.5*Math.PI,1.5*Math.PI,true); cxt.moveTo(0,-1); cxt.arcTo(d,0,0,1,Math.sqrt(1+d*d)/d); } function drawStar(cxt,x,y,R,fillColor){ cxt.save(); cxt.translate(x,y); cxt.rotate(360*Math.random()*Math.PI/180); cxt.scale(R,R); starPath(cxt); cxt.fillStyle = fillColor; cxt.fill(); cxt.restore(); } function starPath(cxt){ cxt.beginPath(); for(var i=0;i<5;i++){ cxt.lineTo(Math.cos((18+72*i)*Math.PI/180),-Math.sin((18+72*i)*Math.PI/180)); cxt.lineTo(Math.cos((54+72*i)*Math.PI/180)*0.5,-Math.sin((54+72*i)*Math.PI/180)*0.5); } cxt.closePath(); }
该实例来自慕课网的学习,感兴趣的朋友可以去学习一下哦~