用canvas实现流星雨拖影效果

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>拖影动画</title>
<style>
canvas{
border: 1px solid #000;
}
</style>
<script>
/*我不相信有天堂,因为我被困在这个地狱的时间太长了*/
</script>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var radius = 20, width = 400, height = 400;
function toAngle(radian){
return 180*radian/Math.PI;
}
function toRadian(angle){
return Math.PI*angle/180;
}//转换成弧度
var canvas=document.getElementById('canvas'),
ctx=canvas.getContext('2d');//定义2d动画效果
ctx.fillStyle = "blue";//设置填充色
ctx.arc(25, 30, 20, 0, 2 * Math.PI);//创建一个圆
ctx.fill();//调用填充色

var stepX = 3;//设置运行的步数
var stepY = 2;
var x = 25,
y = 30;
window.requestAnimationFrame(function render(){//创建动画函数
if(x+20>canvas.width||x<20){//判断x移动的长度
x = getRandomNum();//获得x的随机数
}
if(y+20>canvas.height||y<20){
y = getRandomNum();
}
x+=stepX;
y+=stepY*0.98+0.25;

ctx.save();//调用save保存状态,此包括移动,旋转,缩放
ctx.fillStyle="rgba(255,255,255,0.3)";//设置填充的颜色
ctx.fillRect(0,0,canvas.width,canvas.height);//绘制已填充的图形
ctx.restore();//restore() 返回最新的保存状态

ctx.beginPath();//beginPath() 方法在一个画布中开始子路径的一个新的集合。
ctx.arc(x,y,20,0,2*Math.PI);
ctx.fill();
window.requestAnimationFrame(render);
})
function getRandomNum() {//获取随机数
return Math.random() * (width - radius * 2) + radius;
}
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/Gabriels/p/6305905.html