html5 流星雨,canvas简单流星雨

function lx(obj) {

this.Id = obj.id;

this.src = obj.src; //图片地址

this.img = ''; //图片

this.cxt = ''; //canvas实例

this.Time = ""; //定时器控制流星运动

this.Time2 = ""; //定时器创建流星

this.sum = 500; //流星出现频率

this.beginIpY = []; //流星初始位置

this.beginIpX = [];

this.sd = []; //每个流星的速度

this.init(); //初始化

}

lx.prototype = {

init: function() {

// 布局

var c = document.getElementById(this.Id);

c.setAttribute("width", window.innerWidth * 2);

c.setAttribute("height", window.innerHeight * 2);

var cxt = c.getContext("2d");

this.cxt = cxt;

this.insta();

},

// canvas背景

insta: function() {

var that = this;

that.positionStar()

},

// 创建星星

newStar: function() {

this.cxt.clearRect(0, 0, window.innerWidth * 2, window.innerHeight * 2);

this.cxt.strokeStyle = '#fff';

this.cxt.lineCap = 'round';

this.cxt.lineWidth = 4;

for (var i = 0; i < this.beginIpY.length; i++) {

var xw = Math.floor(Math.random() * 10 * window.innerHeight) + 500;

var ctx = this.cxt;

if (this.beginIpY[i] >= xw) {

this.beginIpX.splice(i, 1);

this.beginIpY.splice(i, 1);

this.sd.splice(i, 1);

} else {

this.beginIpX[i] = this.beginIpX[i] + this.sd[i];

this.beginIpY[i] = this.beginIpY[i] + this.sd[i];

//径向渐变,从流星头尾圆心,半径越大,透明度越高

var gra = ctx.createRadialGradient(

this.beginIpX[i], this.beginIpY[i], 0, this.beginIpX[i], this.beginIpY[i], 50)

var PI = Math.PI

gra.addColorStop(0, '#FFFFFF')

gra.addColorStop(1, 'rgba(0,0,0,0)')

ctx.fillStyle = gra

ctx.beginPath()

//流星头,二分之一圆

ctx.arc(this.beginIpX[i], this.beginIpY[i], 2, -PI / 4, -5 * PI / 4)

//绘制流星尾,三角形

ctx.lineTo(this.beginIpX[i] - 50, this.beginIpY[i] - 50)

ctx.closePath()

ctx.stroke();

}

}

},

//流星定位

positionStar: function() {

for (var i = 0; i < 1; i++) {

var xw = Math.floor(Math.random() * 2000);

var wt = Math.floor(Math.random() * 30);

var sd = Math.floor(Math.random() * 4) + 2;

// 开始位置

this.beginIpX.push(xw);

this.beginIpY.push(wt);

this.sd.push(sd);

}

this.starAnimet();

},

//添加星星运动

starAnimet: function() {

var that = this;

this.Time = setInterval(function() {

that.newStar();

}, 1);

this.pushStarfun();

},

// 定时添加流星雨

pushStarfun: function() {

var that = this;

this.Time2 = setInterval(function() {

if (that.beginIpY.length < 5) {

var xw = Math.floor(Math.random() * 2000);

var wt = Math.floor(Math.random() * 30);

var sd = Math.floor(Math.random() * 4) + 2;

// 开始位置

that.beginIpX.push(xw);

that.beginIpY.push(wt);

that.sd.push(sd);

}

}, this.sum)

}

}

var aa = new lx({

id: "myCanvas",

src: "http://www.jq22.com/img/cs/500x500-1.png",

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值