canvas+js绘制星空页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
overflow: hidden;
}
#canvas{
display: block;
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var w,h;
var rainCount = 20;
var num = 200;
var rains = [];
var data =[];
var cxt;
init();
function init(){
canvas = document.getElementById("canvas");
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
cxt = canvas.getContext("2d");
}
window.onload = function(){
init2();AAAAAAAAAAAAAAAAAAA
for(var i=0;i<rainCount;i++){
var rain = new Meteor();
rain.init();
rain.draw();
rains.push(rain);
}
meteorMove();
}
function init2(){
for(var i=0;i<num;i++){
data[i] = {
x:Math.random()*w,
y:Math.random()*h,
cX:Math.random()*0.6-0.3,
cY:Math.random()*0.6-0.3
};
cricle(data[i].x,data[i].y);
}
}
function cricle(x,y){
var c = Math.random();
cxt.save();
cxt.beginPath();
cxt.arc(x,y,1,0,2*Math.PI);
cxt.fillStyle = "pink";
cxt.fill();
cxt.closePath();
cxt.restore();
}
var Meteor = function(){
this.x = -1;
this.y = -1;
this.width = -1;
this.height = -1;
this.length = -1;
this.angle = 0;
this.offset_x =0;
this.offset_y =0;
this.speed = 0;
this.color1 = "";
this.color2 = "";
this.init = function(){
this.x = w*Math.random();
this.y = h*Math.random();
this.rainColor();
this.length = Math.ceil(Math.random()*60+170);
this.angle = 30;
this.width = this.length*(Math.cos(this.angle*3.14/180));
this.height = this.length*(Math.sin(this.angle*3.14/180));
}
this.rainColor = function(){
var c =255-parseInt(Math.random()*240);
this.color1 = "rgba("+c+",20,100,0.5)";
this.color2 = "#000000";
}
this.draw = function(){
cxt.save();
cxt.beginPath();
cxt.lineWidth = 1;
var gradient = cxt.createLinearGradient(this.x,this.y,this.x-this.width,this.y-this.height);
gradient.addColorStop(0,"white");
gradient.addColorStop(0.3,this.color1);
gradient.addColorStop(0.6,this.color2);
cxt.strokeStyle = gradient;
cxt.moveTo(this.x,this.y);
cxt.lineTo(this.x-this.width,this.y-this.height);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
this.move = function(){
this.speed = Math.random()*2;
this.offset_x = this.speed*Math.cos(this.angle*3.14/180);
this.offset_y = this.speed*Math.sin(this.angle*3.14/180);
this.x = this.x+this.offset_x;
this.y = this.y+this.offset_y;
this.draw();
}
}
function meteorMove(){
for(var i=0;i<rainCount;i++){
rains[i].move();
if(rains[i].y>=window.innerHeight || rains[i].y>=window.innerWidth){
cxt.clearRect(rains[i].x-rains[i].width,rains[i].y-rains[i].height,rains[i].width,rains[i].height);
rains[i] = new Meteor();
rains[i].init();
}
}
setTimeout("meteorMove()",2);
}
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5cd7cac325b2c57be3ff2b7f8c5a4b57.png#pic_center)