红包雨
要构建一个红包雨,首先我们要画一个红包,所以我用了一个红包函数hongbao
function hongbao(){context.beginPath();context.strokeStyle="red";context.lineJoin="round";context.lineWidth=10;context.strokeRect(0,0,30,50);context.stroke();context.lineWidth=5;context.strokeStyle="white";context.arc(15,0,15,0,Math.PI);context.stroke();context.fillStyle="red";context.fillRect(5,5,20,40);context.fill();context.fillStyle="white";context.font="20px Aprial";context.fillText("抢",5,35);context.closePath();}
接下来为了实现红包一个整体不断下落的情况,我用了context.translate()函数,它是用来改变原点的,每一次改变原点就会造成红包每一次显示的位置会不同,同时每一个红包用关联数组来装,这样通过一个循环就可以画出在不同位置的多个红包
var points=new Array(); //红包用关联数组来装
for(var i=0;i<points.length;i++)
{context.save();context.translate(points[i].x,points[i].y);hongbao();context.restore();
}
然后我们用一个for循环来产生10个随机位置和下落速度红包
for(var i=0;i<10;i++)
{tx=Math.floor(Math.random()*800); //在画布大小上随机取一个x点ty=Math.floor(Math.random()*400);//在画布大小上随机取一个y点tspeed=Math.floor(Math.random()*3+1);//红包运行速度1~4随机取points.push({x:tx,y:ty,speed:tspeed});//将红包信息放到数组中
}
接下来每次当红包落出画布外,我们就把这个红包删掉,同时增加一个随机位置红包
if(points[i].y>=400)
{points.splice(i,1);tx=Math.floor(Math.random()*800);ty=Math.floor(Math.random()*400);tspeed=Math.floor(Math.random()*3+1);points.push({x:tx,y:ty,speed:tspeed});
}
好了,废话不多说了,直接上全部代码
<!DOCTYPE html>
<html>
<head><title>红包</title>
</head>
<body><canvas id="mycanvas" height="400" width="800"></canvas><script type="text/javascript">var c=document.getElementById("mycanvas");var context=c.getContext("2d");var points=new Array();var tx;var ty;var count=0;var tspeed;for(var i=0;i<10;i++){block();}function block(){tx=Math.floor(Math.random()*800);ty=Math.floor(Math.random()*400);tspeed=Math.floor(Math.random()*3+1);points.push({x:tx,y:ty,speed:tspeed});}function envelope(){context.clearRect(0,0,800,400);context.font="30px Aprial";context.fillText("你的红包数是"+count,10,30);for(var i=0;i<points.length;i++){context.save();context.translate(points[i].x,points[i].y);hongbao();context.restore();points[i].y=points[i].y+points[i].speed;if(points[i].y>=400){points.splice(i,1);block();}}mycanvas.onmousedown=function(e){var l = e.clientX - mycanvas.offsetLeft; var t = e.clientY - mycanvas.offsetTop;for(var i=0;i<points.length;i++){if((points[i].x<l&&l<points[i].x+30)&&(points[i].y<t&&points[i].y+50>t)){points.splice(i,1);block();count++;}}}if(count==10){context.font="30px Aprial";context.fillStyle="black";context.fillText("游戏结束",300,200);clearInterval(pl);}}function hongbao(){context.beginPath();context.strokeStyle="red";context.lineJoin="round";context.lineWidth=10;context.strokeRect(0,0,30,50);context.stroke();context.lineWidth=5;context.strokeStyle="white";context.arc(15,0,15,0,Math.PI);context.stroke();context.fillStyle="red";context.fillRect(5,5,20,40);context.fill();context.fillStyle="white";context.font="20px Aprial";context.fillText("抢",5,35);context.closePath();}var pl=setInterval(envelope,10);</script>
</body>
</html>